Best Python code snippet using fMBT_python
server.py
Source:server.py  
1import os2import json3from flask import Flask, redirect, request,render_template, jsonify, session, make_response, escape, flash4import sqlite35import math6from datetime import date7from PIL import Image8from PIL.ExifTags import TAGS, GPSTAGS9# Below 4 lines are for Geocode coordinate and error handling for all geocoder files10# FOR THIS TO WORK YOU NEED TO ON YOUR CMD TO DO THIS: pip install opencage11from opencage.geocoder import OpenCageGeocode12from opencage.geocoder import InvalidInputError, RateLimitExceededError, UnknownError13from werkzeug.utils import secure_filename14key = 'd0d06fa6997b4770af8c48796657cbf0'15geocoder = OpenCageGeocode(key)16APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # This says where the server is stored on the device17UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads') # This adds the folder where the tap pictures are going to be stored18DATABASE = 'databases/main_db.db'19app = Flask(__name__)20app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER21ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])22directory = []23app.secret_key = 'fj590Rt?h40gg'24def allowed_file(filename):25    ext = filename.rsplit('.', 1)[1].lower()26    return '.' in filename and ext in ALLOWED_EXTENSIONS27# DeLancey, J. (2019). Getting Started with Geocoding Exif Image Metadata in Python 3 - HERE Developer. [online] HERE Developer Blog. Available at: https://developer.here.com/blog/getting-started-with-geocoding-exif-image-metadata-in-python3 [Accessed 8 Dec. 2019].28def get_exif(filename):29    image = Image.open(filename)30    image.verify()31    return image._getexif()32def get_geotagging(exif):33    geotagging = {}34    if exif == None:35        pass36    else:37        for (idx, tag) in TAGS.items():38            if tag == 'GPSInfo':39                if idx not in exif:40                    return None41                for (key, val) in GPSTAGS.items():42                    if key in exif[idx]:43                        geotagging[val] = exif[idx][key]44    return geotagging45def get_decimal_from_dms(dms, ref):46    degrees = dms[0][0] / dms[0][1]47    minutes = dms[1][0] / dms[1][1] / 60.048    seconds = dms[2][0] / dms[2][1] / 3600.049    if ref in ['S', 'W']:50        degrees = -degrees51        minutes = -minutes52        seconds = -seconds53    return round(degrees + minutes + seconds, 5)54def get_coordinates(geotags):55    if geotags == None:56        lat = None57        lon = None58    elif len(geotags) == 0:59        lat = None60        lon = None61    else:62        lat = get_decimal_from_dms(geotags['GPSLatitude'], geotags['GPSLatitudeRef'])63        lon = get_decimal_from_dms(geotags['GPSLongitude'], geotags['GPSLongitudeRef'])64    return (lat,lon)65# finish reference66# lines 65 - 77 Janakiev, N. (2019). Calculate Distance Between GPS Points in Python. [online] Parametric Thoughts. Available at: https://janakiev.com/blog/gps-points-distance-python/ [Accessed 8 Dec. 2019].67def getDistance(latitude1, longitude1, latitude2, longitude2):68    R = 6372800  # Earth radius in meters69    lat1, lon1 = (latitude1, longitude1)70    lat2, lon2 = (latitude2, longitude2)71    phi1, phi2 = math.radians(lat1), math.radians(lat2)72    dphi       = math.radians(lat2 - lat1)73    dlambda    = math.radians(lon2 - lon1)74    a = math.sin(dphi/2)**2 + \75        math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**276    d = 2*R*math.atan2(math.sqrt(a), math.sqrt(1 - a))77    # finish reference78    if d <= 10: # This is 10 m (I think)79        return True80    else:81        return False82@app.route("/AddComment", methods = ['POST'])83def AddComment():84    if request.method =='POST':85        user_comment = request.json['commentData']86        tap_id = request.json['tapID']87        userId = session['userID']88        try:89            conn = sqlite3.connect(DATABASE)90            cur = conn.cursor()91            cur.execute("INSERT INTO reviews ('comment', 'date', 'tapID', 'userID')\92                            VALUES (?,date(julianday('now')),?,?)",(user_comment, tap_id, userId) )93            conn.commit()94        except:95            print('there was an error 0')96            conn.rollback()97        finally:98            conn.close()99    return "sucess"100@app.route("/", methods = ['GET'])101def HomeRedirect():102    if request.method =='GET':103        return redirect('/home')104@app.route("/home", methods = ['GET'])105def HomePage():106    if request.method =='GET':107        return render_template('HomePage.html')108@app.route("/home/about", methods = ['GET'])109def AboutPage():110    if request.method =='GET':111        return render_template('About.html')112@app.route("/home/about/why" , methods = ['GET'])113def WhyUseTapspage():114    if request.method =='GET':115        return render_template('FAQ.html')116@app.route("/home/taps/near/page=$<pagenum>$/!lat=<user_lat>&lng=<user_lng>", methods = ['GET'])117def NearTapPage(pagenum, user_lat, user_lng):118    if request.method =='GET':119        try:120            conn = sqlite3.connect(DATABASE)121            cur = conn.cursor()122            # SQL command to order list by distance from longitude and latitude123            # Author:  statickidz124            # Date: 25/11/2019125            # Link: https://gist.github.com/statickidz/8a2f0ce3bca9badbf34970b958ef8479126            cur.execute("SELECT * FROM taps ORDER BY ((latitude-?)*(latitude-?)) + ((longitude - ?)*(longitude - ?)) ASC LIMIT ?, 5;", (user_lat, user_lat, user_lng, user_lng, int(pagenum)*5))127            data = cur.fetchall()128        except:129            print('there was an error 1')130            conn.close()131        finally:132            conn.close()133        all_tap_data = []134        for item in data:135            try:136                tapImage = Image.open(f"{APP_ROOT}{item[4]}",mode='r')137                tapImageRoute = item[4]138            except Exception as e:139                print(e)140                tapImageRoute = "http://placehold.it/750x300"141                print("failed to load")142            try:143                conn = sqlite3.connect(DATABASE)144                cur = conn.cursor()145                cur.execute("SELECT id, username FROM users WHERE id IS ?;", (str(item[5])))146                userdata = cur.fetchall()147                userdata = userdata[0]148            except:149                print('there was an error 2')150                conn.close()151            finally:152                conn.close()153            one_tap_data = {'TapID': item[0], 'Address': item[1], 'Longitude': item[3], 'Latitude': item[2], 'Image': tapImageRoute, 'Description': item[7], 'PostDate': item[6], 'UserLink': '/home/users/' + str(userdata[0]) + '/info', 'UserName': userdata[1]}154            all_tap_data.append(one_tap_data)155        return render_template('TapList.html', alltapdata = all_tap_data)156@app.route("/home/taps/search=£<search>£/page=$<pagenum>$/!lat=<user_lat>&lng=<user_lng>", methods = ['GET'])157def SearchTapPage(search, pagenum, user_lat, user_lng):158    if request.method =='GET':159        try:160            conn = sqlite3.connect(DATABASE)161            cur = conn.cursor()162            # SQL command to order list by distance from longitude and latitude163            # Author:  statickidz164            # Date: 25/11/2019165            # Link: https://gist.github.com/statickidz/8a2f0ce3bca9badbf34970b958ef8479166            cur.execute("SELECT * FROM taps WHERE address LIKE ? ORDER BY ((latitude-?)*(latitude-?)) + ((longitude - ?)*(longitude - ?)) ASC LIMIT ?, 5;", ("%"+search+"%", user_lat, user_lat, user_lng, user_lng, int(pagenum)*5))167            data = cur.fetchall()168        except:169            print('there was an error 3')170            conn.close()171        finally:172            conn.close()173        all_tap_data = []174        for item in data:175            try:176                tapImage = Image.open(f"{APP_ROOT}{item[4]}",mode='r')177                tapImageRoute = item[4]178            except Exception as e:179                print(e)180                tapImageRoute = "http://placehold.it/750x300"181                print("failed to load")182            try:183                conn = sqlite3.connect(DATABASE)184                cur = conn.cursor()185                cur.execute("SELECT id, username FROM users WHERE id IS ?;", (str(item[5])))186                userdata = cur.fetchall()187                userdata = userdata[0]188            except:189                print('there was an error 4')190            finally:191                conn.close()192            one_tap_data = {'TapID': item[0], 'Address': item[1], 'Longitude': item[3], 'Latitude': item[2], 'Image': tapImageRoute, 'Description': item[7], 'PostDate': item[6], 'UserLink': '/home/users/' + str(userdata[0]) + '/info', 'UserName': userdata[1]}193            all_tap_data.append(one_tap_data)194        return render_template('TapList.html', alltapdata = all_tap_data)195@app.route("/home/taps/<tapID>/info", methods = ['GET'])196def TapInfo(tapID):197    if request.method =='GET':198        try:199            conn = sqlite3.connect(DATABASE)200            cur = conn.cursor()201            cur.execute("SELECT * FROM taps WHERE id IS ?", [tapID])202            data = cur.fetchall()203            item = data[0]204        except:205            print('there was an error 5')206            conn.close()207        finally:208            conn.close()209        try:210            tapImage = Image.open(f"{APP_ROOT}{item[4]}",mode='r')211            tapImageRoute = item[4]212        except Exception as e:213            print(e)214            tapImageRoute = "http://placehold.it/900x300"215            print("failed to load")216        try:217            conn = sqlite3.connect(DATABASE)218            cur = conn.cursor()219            cur.execute("SELECT username FROM users WHERE id IS ?;", (str(item[5])))220            userdata = cur.fetchall()221            username = userdata[0][0]222        except:223            print('there was an error 6')224            conn.close()225        finally:226            conn.close()227        try:228            conn = sqlite3.connect(DATABASE)229            cur = conn.cursor()230            cur.execute("SELECT * from reviews WHERE tapID IS ?", ([str(item[0])]))231            commentdata = cur.fetchall()232        except:233            print('there was an error 7')234            commentdata = []235            conn.close()236        finally:237            conn.close()238        all_comment_data = []239        for comment in commentdata:240            try:241                conn = sqlite3.connect(DATABASE)242                cur = conn.cursor()243                cur.execute("SELECT id, userName from users WHERE id IS ?", (str(comment[4])))244                commentuserdata = cur.fetchall()245                commentuserdata = commentuserdata[0]246            except:247                print('there was an error 8')248                conn.close()249            finally:250                conn.close()251            one_comment_data= {'data': comment[1], 'date': comment[2], 'userLink': '/home/users/' + str(commentuserdata[0]) + '/info', 'username': commentuserdata[1]}252            all_comment_data.append(one_comment_data)253        one_tap_data = {'TapID': item[0], 'Address': item[1], 'Longitude': item[3], 'Latitude': item[2], 'Image': tapImageRoute, 'Description': item[7], 'PostDate': item[6], 'UserLink': '/home/users/' + str(item[5]) + '/info', 'UserName': username}254        return render_template('TapInfo.html', alltapdata = one_tap_data, allcommentdata = all_comment_data)255@app.route("/home/taps/<tapID>/location", methods = ['GET'])256def MapPage(tapID):257    if request.method =='GET':258        try:259            conn = sqlite3.connect(DATABASE)260            cur = conn.cursor()261            cur.execute("SELECT latitude, longitude, address FROM taps WHERE id IS ?", [tapID])262            data = cur.fetchall()263            data = data[0]264        except:265            print('there was an error 9')266            conn.close()267        finally:268            conn.close()269        return render_template('PlainMap.html', lat = data[0], lng = data[1], address = data[2])270@app.route("/home/users/<userID>/info", methods = ['GET'])271def UserInfo(userID):272    if request.method =='GET':273        try:274            conn = sqlite3.connect(DATABASE)275            cur = conn.cursor()276            cur.execute("SELECT username FROM users WHERE id IS ?;", [userID])277            data = cur.fetchall()278            data = data[0]279        except:280            print('there was an error')281            conn.close()282        finally:283            conn.close()284        try:285            conn = sqlite3.connect(DATABASE)286            cur = conn.cursor()287            cur.execute("SELECT id, address, picture, description FROM taps WHERE userID IS ? ORDER BY postDate DESC Limit 4;", [userID])288            tapdata = cur.fetchall()289        except:290            print('there was an error')291            conn.close()292        finally:293            conn.close()294        all_tap_data = []295        for item in tapdata:296            try:297                tapImage = Image.open(f"{APP_ROOT}{item[2]}",mode='r')298                tapImageRoute = item[2]299            except Exception as e:300                print(e)301                tapImageRoute = "https://placehold.it/700x400?text=Tap+Image+Here"302                print("failed to load")303            one_tap_data = {'TapID': item[0], 'Address': item[1], 'Picture': tapImageRoute, 'Description': item[3]}304            all_tap_data.append(one_tap_data)305        return render_template('UserInfo.html', userdata=data, alltapdata=all_tap_data)306@app.route("/home/taps/new/auto", methods = ['GET', 'POST'])307def NewTapPageAuto():308    msg = ''309    if request.method == 'GET':310        return render_template('addTapAuto.html')311    if request.method == 'POST':312        latitude = float(request.form["latitude"])313        longitude = float(request.form["longitude"])314        address = geocoder.reverse_geocode(latitude, longitude, language='en', no_annotations='1')315        address = address[0]['formatted']316        picture = request.files['picture']317        # if user does not select file, browser also submit a empty part without filename318        try:319            conn = sqlite3.connect(DATABASE)320            cur = conn.cursor()321            if len(session) != 0:322                userId = session['userID']323            else:324                userId = 1325            cur.execute("SELECT latitude, longitude FROM taps WHERE latitude=? AND  longitude=?", (latitude, longitude))326            coor_exist = cur.fetchall()327            if len(coor_exist) == 0: # THIS IF STATEMENT MAKES SURE THAT TAPS THAT ALREADY EXIST IN THE DATABASE CANNOT BE INPUTTEED AGAIN328                if picture.filename == '': # This means that no picture was given329                        msg = "You have no picture, using manual to select location"330                        flash(msg)331                        return redirect('manual')332                else:333                    img_data = get_exif(picture)334                    geotags = get_coordinates(get_geotagging(img_data))335                    if geotags[0] and geotags[1] != None:336                        dist = getDistance(float(geotags[0]), float(geotags[1]), latitude, longitude)337                    else:338                        msg = "Picture doesn't have coordinates, please input the tap's location manualy"339                        flash(msg)340                        return redirect('manual')341                    if dist == True:342                        cur.execute("INSERT INTO taps (address, latitude, longitude, picture, userID, postDate) VALUES (?,?,?,?,?,date(julianday('now')))",343                        (address, latitude, longitude, f"/static/uploads/{picture.filename}", userId))344                        if picture and allowed_file(picture.filename): # we already know that a picture was given345                            filename = secure_filename(picture.filename)346                            filePath = os.path.join(app.config['UPLOAD_FOLDER'], filename)347                            if not os.path.exists(app.config['UPLOAD_FOLDER']):348                                os.makedirs(app.config['UPLOAD_FOLDER'])349                            picture.save(filePath)350                            msg = "Tap & Picture saved"351                        conn.commit()352                        flash(msg)353                        return redirect('/home')354                    elif dist == False:355                        msg = "You and the picture are not close enough"356                        flash(msg)357                        return redirect('manual')358            else:359                msg = "Tap already exists in the database"360                flash(msg)361                return redirect('auto')362        except Exception as e:363            msg = e364            conn.rollback()365            flash(msg)366            return redirect('manual')367        finally:368            conn.close()369@app.route("/home/taps/new/manual", methods = ['GET', 'POST'])370def NewTapPageManual():371    msg = ''372    if request.method == 'GET':373        return render_template('addTapManual.html')374    if request.method == 'POST':375        latitude = float(request.form["latitude"])376        longitude = float(request.form["longitude"])377        address = geocoder.reverse_geocode(latitude, longitude, language='en', no_annotations='1')378        address = address[0]['formatted']379        picture = request.files['picture']380        # if user does not select file, browser also submit a empty part without filename381        try:382            conn = sqlite3.connect(DATABASE)383            cur = conn.cursor()384            if len(session) != 0:385                userId = session['userID']386            else:387                userId = 1388            cur.execute("SELECT latitude, longitude FROM taps WHERE latitude=? AND  longitude=?", (latitude, longitude))389            coor_exist = cur.fetchall()390            if len(coor_exist) == 0: # THIS IF STATEMENT MAKES SURE THAT TAPS THAT ALREADY EXIST IN THE DATABASE CANNOT BE INPUTTEED AGAIN391                if picture.filename == '': # This means that no picture was given392                    cur.execute("INSERT INTO taps (address, latitude, longitude, picture, userID, postDate) VALUES (?,?,?,?,?,date(julianday('now')))",393                    (address, latitude, longitude, None, userId))394                    conn.commit()395                    msg = "Tap saved"396                else:397                    cur.execute("INSERT INTO taps (address, latitude, longitude, picture, userID, postDate) VALUES (?,?,?,?,?,date(julianday('now')))",398                    (address, latitude, longitude, f"/static/uploads/{picture.filename}", userId))399                    if picture and allowed_file(picture.filename): # we already know that a picture was given400                        filename = secure_filename(picture.filename)401                        filePath = os.path.join(app.config['UPLOAD_FOLDER'], filename)402                        if not os.path.exists(app.config['UPLOAD_FOLDER']):403                            os.makedirs(app.config['UPLOAD_FOLDER'])404                        picture.save(filePath)405                        msg = "Tap & Picture saved"406                    conn.commit()407                return redirect('/home')408            else:409                flash("Tap already exists in the database")410                return redirect('manual')411        except Exception as e:412            print(e)413            conn.rollback()414            flash("There was an error inserting the tap")415            return redirect('manual')416        finally:417            conn.close()418@app.route("/givetaps", methods = ['POST'])419def GiveTaps():420    if request.method =='POST':421        user_lat = request.json['lat']422        user_lng = request.json['lng']423        try:424            conn = sqlite3.connect(DATABASE)425            cur = conn.cursor()426            # SQL command to order list by distance from longitude and latitude427            # Author:  statickidz428            # Date: 25/11/2019429            # Link: https://gist.github.com/statickidz/8a2f0ce3bca9badbf34970b958ef8479430            cur.execute("SELECT id, address, latitude, longitude, picture FROM taps ORDER BY ((latitude-?)*(latitude-?)) + ((longitude - ?)*(longitude - ?)) ASC;", (user_lat, user_lat, user_lng, user_lng))431            data = cur.fetchall()432        except:433            print('there was an error 11')434            conn.close()435        finally:436            conn.close()437        all_tap_data = []438        for item in data:439            try:440                tapImage = Image.open(f"{APP_ROOT}{item[4]}",mode='r')441                tapImage = item[4]442            except Exception as e:443                print(e)444                tapImage = "https://placehold.it/500?text=Tap+Image+Here"445                print("failed to load")446            one_tap_data = {'ID': item[0], 'Address': item[1], 'Lat': item[2], 'Lng': item[3], 'Image': tapImage}447            all_tap_data.append(one_tap_data)448        return jsonify(all_tap_data)449@app.route("/home/faq", methods = ['GET'])450def FAQPage():451    if request.method =='GET':452        return render_template('FAQ.html')453@app.route("/home/about/contact", methods = ['GET'])454def ContactPage():455    if request.method =='GET':456        return render_template('Contact.html')457@app.route("/home/taps/comments", methods = ['GET'])458def CommentsPage():459	if request.method =='GET':460		return render_template('CommentsTaps.html')461@app.route("/home/login/admin", methods = ['GET', 'POST'])462#code for deleting a row in a database: DELETE FROM "main"."users" WHERE _rowid_ IN ('1');463def AdminPage():464    # if session.get('admin') is not True:465    #     return redirect("/", code=302)466    username = request.cookies.get('username')467    usertype = "null"468    if 'usertype' in session:469        usertype = escape(session['usertype'])470    if usertype == "Admin":471        if request.method =='GET':472            return render_template('adminPage.html', msg = '', username = username)473    else:474        return render_template('HomePage.html', username = username)475@app.route("/home/signup", methods = ['GET','POST'])476def SignupPage():477    if request.method =='GET':478        return render_template('Signup.html')479    if request.method =='POST':480        usern = request.form.get('UN', default="Error")481        passw = request.form.get('PW', default="Error")482        try:483            conn = sqlite3.connect(DATABASE)484            cur = conn.cursor()485            cur.execute("INSERT INTO users ('userName', 'password', 'role')\486                        VALUES (?,?,?)",(usern, passw, '0') )487            conn.commit()488        except:489            conn.rollback()490            return redirect("/", code=302)491        finally:492            conn.close()493            return render_template('Signup.html')494@app.route("/home/login", methods = ['GET','POST'])495def LoginPage():496    if request.method =='GET':497        return render_template('login_page.html')498    if request.method=='POST':499        uName = request.form.get('username', default="Error")500        pw = request.form.get('password', default="Error")501        conn = sqlite3.connect(DATABASE)502        cur = conn.cursor()503        cur.execute("SELECT id, role FROM users WHERE userName IS ? AND password IS ?", (uName, pw))504        data = cur.fetchall()505        data = data[0]506        # conn.commit()507        if data[1] == 1:508            session['usertype'] = 'Admin'509            session['userID'] = data[0]510            return redirect("/home/login/admin", code=302)511        else:512            session['usertype'] = 'Customer'513            session['userID'] = data[0]514            return redirect("/home", code=302)515    else:516        return render_template('login_page.html')517@app.route("/home/login/admin/tapsDB", methods = ['GET', 'POST'])518def tapsDBPage():519	if request.method =='GET':520            try:521                conn = sqlite3.connect(DATABASE)522                cur = conn.cursor()523                cur.execute("SELECT * FROM taps")524                data = cur.fetchall()525            except:526                print('there was an error 12')527                conn.close()528                return redirect("/home/login/admin", code=302)529            finally:530                conn.close()531                return render_template('tapsAP.html', data = data)532@app.route("/home/login/admin/reviewsDB", methods = ['GET', 'POST'])533def reviewsDBPage():534	if request.method =='GET':535            try:536                conn = sqlite3.connect(DATABASE)537                cur = conn.cursor()538                cur.execute("SELECT * FROM reviews")539                data = cur.fetchall()540            except:541                print('there was an error 13')542                conn.close()543                return redirect("/home/login/admin", code=302)544            finally:545                conn.close()546                return render_template('reviewAP.html', data = data)547@app.route("/home/login/admin/usersDB", methods = ['GET', 'POST'])548def usersDBPage():549	if request.method =='GET':550            try:551                conn = sqlite3.connect(DATABASE)552                cur = conn.cursor()553                cur.execute("SELECT * FROM users")554                data = cur.fetchall()555            except:556                print('there was an error 14')557                conn.close()558                return redirect("/home/login/admin", code=302)559            finally:560                conn.close()561                return render_template('usersAP.html', data = data)562@app.route("/deleteTap", methods = ['DELETE'])563def deleteTapPage():564	if request.method =='DELETE':565            tapDelete = request.form.get('idDelete', default="Error")566            try:567                conn = sqlite3.connect(DATABASE)568                cur = conn.cursor()569                cur.execute("DELETE FROM taps WHERE id IS ?;", (tapDelete))570                conn.commit()571            except:572                print('there was an error 15')573                conn.rollback()574            finally:575                conn.close()576                return "Success"577@app.route("/deleteUser", methods = ['DELETE'])578def deleteUserPage():579	if request.method =='DELETE':580            userDelete = request.form.get('idDelete', default="Error")581            try:582                conn = sqlite3.connect(DATABASE)583                cur = conn.cursor()584                cur.execute("DELETE FROM users WHERE id IS ?;", (userDelete))585                conn.commit()586            except:587                print('there was an error 16')588                conn.rollback()589            finally:590                conn.close()591                return "Success"592@app.route("/deleteReview", methods = ['DELETE'])593def deleteReviewPage():594	if request.method =='DELETE':595            reviewDelete = request.form.get('idDelete', default="Error")596            try:597                conn = sqlite3.connect(DATABASE)598                cur = conn.cursor()599                cur.execute("DELETE FROM reviews WHERE id IS ?;", (reviewDelete))600                conn.commit()601            except:602                print('there was an error 17')603                conn.rollback()604            finally:605                conn.close()606                return "Success"607@app.errorhandler(404)608def page_not_found(e):609    return render_template('404.html'), 404610if __name__ == "__main__":...sensor.py
Source:sensor.py  
1import sys2import json3from tabulate import tabulate4from fastscore import Sensor5from fastscore import FastScoreError6from .editor import run_editor7def add(connect, name, descfile=None, verbose=False, **kwargs):8    try:9        if descfile:10            with open(descfile) as f:11                desc = f.read()12        else:13            desc = sys.stdin.read()14        sensor = Sensor(name, json.loads(desc))15    except Exception as e:16        raise FastScoreError("Unable to add sensor '%s'" % name, caused_by=e)17    mm = connect.lookup('model-manage')18    updated = sensor.update(mm)19    if verbose:20        print "Sensor updated" if updated else "Sensor created"21def show(connect, name, edit=False, verbose=False, **kwargs):22    mm = connect.lookup('model-manage')23    sensor = mm.sensors[name]24    if edit:25        desc = json.dumps(sensor.desc, indent=2)26        desc1 = run_editor(desc, "SENSOR_EDITING")27        if desc1 != None:28            try:29                sensor.desc = json.loads(desc1)30            except:31                raise FastScoreError("Invalid JSON")32            sensor.update()33            if verbose:34                print "Sensor updated"35        else:36            if verbose:37                print "No changes (or changes discarded)"38    else:39        print json.dumps(sensor.desc, indent=2)40def remove(connect, name, verbose=False, **kwargs):41    mm = connect.lookup('model-manage')42    del mm.sensors[name]43    if verbose:44        print "Sensor removed"45def roster(connect, verbose=False, asjson=False, **kwargs):46    mm = connect.lookup('model-manage')47    if asjson:48        print json.dumps(mm.sensors.names(), indent=2)49    else:50        for x in mm.sensors.names():51            print x52def install(connect, name, verbose=False, **kwargs):53    if not connect.target:54        raise FastScoreError("Target not selected (see 'fastscore use')")55    mm = connect.lookup('model-manage')56    sensor = mm.sensors[name]57    sid = sensor.install(connect.target)58    if verbose:59        print "Sensor installed [%s]" % sid60    else:61        print sid62def uninstall(connect, tapid, verbose=False, **kwargs):63    n = toint(tapid)64    if not connect.target:65        raise FastScoreError("Target not selected (see 'fastscore use')")66    mm = connect.lookup('model-manage')67    sensors = connect.target.active_sensors68    if not n in sensors:69        raise FastScoreError("Sensor id %d not found" % n)70    sensors[n].uninstall()71    if verbose:72        print "Sensor uninstalled"73def inspect(connect, tapid=None, verbose=False, asjson=False, **kwargs):74    if not connect.target:75        raise FastScoreError("Target not selected (see 'fastscore use')")76    sensors = connect.target.active_sensors77    if tapid != None:78        n = toint(tapid)79        if not n in sensors:80            raise FastScoreError("Sensor id %d not found" % n)81        if asjson:82            print json.dumps(sensors[n].to_dict(), indent=2)83        else:84            print "Sensor id %d is attached to '%s' at '%s'." \85                    % (n,sensors[n].tap,connect.target.name)86    elif asjson:87        print json.dumps(map(lambda x: x.to_dict(), sensors.values()), indent=2)88    else:89        if verbose:90            print "Sensors installed at '%s':" % connect.target.name91        t = [ [x.id,x.tap] for x in connect.target.active_sensors.values() ]92        print tabulate(t, headers = ["Id","Tap"])93def points(connect, verbose=False, asjson=False, **kwargs):94    if not connect.target:95        raise FastScoreError("Target not selected (see 'fastscore use')")96    if asjson:97        print json.dumps(connect.target.tapping_points, indent=2)98    else:99        if verbose:100            print "Sensor tapping points at '%s':" % connect.target.name101            for x in connect.target.tapping_points:102                print "  " + x103        else:104            for x in connect.target.tapping_points:105                print x106def toint(tapid):107    try:108        return int(tapid)109    except:...config.py
Source:config.py  
1import os2import copy3from .utils import flatmap4from .serializable import Serializable5from .vm import VM6class Config(Serializable):7    def __init__(self, vms):8        self.vms = vms9        self.file = ''10    def add(self, vm):11        self.vms[vm.name] = vm12        return self13    def remove(self, vm_name):14        del self.vms[vm_name]15        return self16    def modify(self, vm):17        return self.add(vm)18    def get(self, vm_name):19        return self.vms[vm_name]20    def clone(self, source, name):21        vm = copy.deepcopy(self.get(source))22        vm.name = name23        vm.nmdm_id = self.new_nmdmid()24        tapid = self.new_tapid()25        for nic in vm.nics:26            nic.name = 'tap' + str(tapid)27            tapid += 128        cmds = []29        for disk in vm.disks:30            new_name = disk.name.replace(source, name)31            for cmd in disk.clone(new_name):32                cmds.append(cmd)33            disk.name = new_name34        self.add(vm)35        return cmds36    def to_dict(self):37        dct = {}38        for k, v in self.vms.items():39            dct[k] = v.to_dict()40            del dct[k]['name']41        return dct42    @classmethod43    def from_dict(cls, dct):44        if dct is None:45            dct = {}46        vms = {}47        for k, v in dct.items():48            v['name'] = k49            vms[k] = VM.from_dict(v)50        return cls(vms)51    @classmethod52    def open(cls, config_file):53        if os.path.exists(config_file):54            with open(config_file) as cf:55                config = cls.load(cf.read())56        else:57            config = cls.from_dict({})58        config.file = config_file59        return config60    def save(self):61        assert self.file62        with open(self.file, 'w') as cf:63            cf.write(self.dump())64    def new_tapid(self):65        max_id = max(map(lambda x: int(x.name[3:]), flatmap(lambda x: x.nics, self.vms.values())))66        return max_id + 167    def new_nmdmid(self):...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!!
