Best Python code snippet using autotest_python
flask_api.py
Source:flask_api.py  
1# encoding=utf-82from flask import Flask, url_for, render_template, request, session, redirect, flash, g, session, jsonify3import  os4from flask_sqlalchemy import SQLAlchemy5import config6import sqlite37from flask import g8from flask_mail import Mail, Message9import folium10from folium.plugins import HeatMap11import geocoder12mail = Mail()13app = Flask(__name__)14app.config.from_object(config)15DATABASE = 'user_feature.db'16mail.init_app(app)17def get_db():18    db = getattr(g, '_database', None)19    if db is None:20        db = g._database = sqlite3.connect(DATABASE)21    return db22@app.teardown_appcontext23def close_connection(exception):24    db = getattr(g, '_database', None)25    if db is not None:26        db.close()27@app.route("/")28def index():29    # msg = Message("Hello, this for test",30    #               sender=app.config["MAIL_USERNAME"],31    #               recipients=["b.ben.hjy@gmail.com"])32    # mail.send(msg)33    return "hello world"34@app.route("/sign_up", methods=["GET", "POST"])35def sign_up():36    if request.method == "GET":37        return render_template("registration.html")38    else:39        username = request.form.get("username")40        email = request.form.get("email")41        cur = get_db()42        cur.execute("delete from user_email where username='{}'".format(username))43        sql_command = "INSERT INTO user_email VALUES ('{}', '{}')".format(username, email)44        cur.execute(sql_command)45        cur.commit()46        # close db47        if cur is not None:48            cur.close()49        return "Sign up successfully"50@app.route("/send/<info>")51def send(info):52    # data should be seperate by "-"53    # username text, latitude  real, Longitude real, temperature real, pressure real, humidity real54    info = info.split("-")55    print(info)56    db = get_db()57    # cur.execute("delete from user_feature where username='{}'".format(info[0]))58    # sql_command = "INSERT INTO user_feature VALUES ('{}',{},{},{},{},{})".format(info[0], info[1], info[2], info[3], info[4], info[5])59    # cur.execute(sql_command)60    # cur.commit()61    cur = db.cursor()62    print(info[0])63    cur.execute("select * from user_email where username='{}'".format(info[0]))64    to_email = cur.fetchall()[0][1]65    msg = Message("Help!!! {} is in danger. The location is {}".format(info[0], info[1]),66                  sender=app.config["MAIL_USERNAME"],67                  recipients=[to_email])68    mail.send(msg)69    # close db70    if db is not None:71        db.close()72    return "Successfully send"73@app.route("/save_data/<info>")74def save_data(info):75    # username-lon-lat-risk76    info = info.split("&")77    print(info)78    username = info[0]79    cur = get_db()80    cur.execute("delete from user_info where username='{}'".format(username))81    sql_command = "INSERT INTO user_info VALUES ('{}', {}, {}, {})".format(username, info[1], info[2], info[3])82    cur.execute(sql_command)83    cur.commit()84    # close db85    if cur is not None:86        cur.close()87    return "save successfully"88@app.route("/heatmap", methods=["GET", "POST"])89def heatmap():90    if request.method == "GET":91        return render_template("heatmap.html")92    else:93        username = request.form.get("username")94        return redirect(url_for("get_heatmap", username=username))95@app.route("/get_heatmap/<username>")96def get_heatmap(username):97    check_dict = dict()98    db = get_db()99    cur = db.cursor()100    # cur.execute("select * from user_info where username='{}'".format(username))101    cur.execute("select * from user_info")102    user_info = cur.fetchall()103    cur.execute("select * from user_email")104    user_email = cur.fetchall()105    target_lon = 0106    target_lat = 0107    for i in range(len(user_info)):108        username1 = user_info[i][0]109        username2 = user_email[i][0]110        email = user_email[i][1]111        lon = user_info[i][1]112        lat = user_info[i][2]113        risk = user_info[i][3]114        if not username1 in check_dict:115            check_dict[username1] = {"email":'', "lat":0, "lon":0, "risk":'0'}116        if not username2 in check_dict:117            check_dict[username2] = {"email": '', "lat": 0, "lon": 0, "risk": '0'}118        check_dict[username1]["lon"] = lon119        check_dict[username1]["lat"] = lat120        check_dict[username1]["risk"] = risk121        check_dict[username2]['email'] = email122    if not username in check_dict:123        return "Cannot find this guy"124    folium_map = folium.Map(location=(check_dict[username]['lon'], check_dict[username]['lat']), zoom_start=14)125    hm_wide = HeatMap( list(zip([check_dict[username]['lon'] ], [check_dict[username]['lat'] ], [check_dict[username]["risk"]])), min_opacity=0.2, max_val=1, radius=20, blur=10, max_zoom=15, )126    folium_map.add_child(hm_wide)127    for key in check_dict.keys():128        folium.Marker((check_dict[key]["lon"], check_dict[key]['lat']), popup="username: "+key+"\n"+"risk: "+str(check_dict[key]['risk'])+ "\n"+check_dict[key]["email"] ).add_to(folium_map)129    # close db130    if db is not None:131        db.close()132    return folium_map._repr_html_()133@app.route("/get/<username>")134def get(username):135    cur = get_db().cursor()136    cur.execute("select * from user_feature where username='{}'".format(username))137    print(cur.fetchall()[0])138    return "get successfully"139if __name__ == '__main__':...WaterJugProblem.py
Source:WaterJugProblem.py  
1import collections23def main():4    start_node = [[0, 0]]5    jugs = get_jugs()6    target_capacity = get_target(jugs)7    check_dict = {}8    search(start_node, jugs, target_capacity, check_dict)910def get_index(node):11    return pow(4, node[0]) * pow(3, node[1])1213#Get volume of the jugs14def get_jugs():15    16    jugs = []17    temp = int(input("Enter first jug volume: "))18    while temp < 1:19            temp = int(input("Enter a valid amount (>1): "))       20    jugs.append(temp)21    22    temp = int(input("Enter second jug volume: "))23    while temp < 1:24            temp = int(input("Enter a valid amount (>1): "))     25    jugs.append(temp)26    27    return jugs28    29#**Desired water capacity30def get_target(jugs):31  32    max_capacity = max(jugs[0], jugs[1])33    s = "Desired water capacity : ".format(max_capacity)34    target_capacity = int(input(s))35    while target_capacity < 1 or target_capacity > max_capacity:36        target_capacity = int(input("Enter a valid amount (1 - {0}): ".format(max_capacity)))37        38    return target_capacity3940##########41#Check the jugs reached to Target capacity42def is_target(path, target_capacity):43    return path[-1][0] == target_capacity or path[-1][1] == target_capacity4445def been_there(node, check_dict):46    print(" {0} is a before visited state ".format(node))47    return check_dict.get(get_index(node), False)4849def next_transitions(jugs, path, check_dict):50   51    print("Search next state/ position")52    result = []53    next_nodes = []54    node = []55    56    a_max = jugs[0]57    b_max = jugs[1]58    59    # Start state Jug 0160    a = path[-1][0]  61    # Start state Jug 0262    b = path[-1][1]  6364    # 1. Fill 4l/ First jug65    node.append(a_max)66    node.append(b)67    if not been_there(node, check_dict):68        next_nodes.append(node)69    node = []7071    # 2. Fill 3l/ Second jug72    node.append(a)73    node.append(b_max)74    if not been_there(node, check_dict):75        next_nodes.append(node)76    node = []7778    # 3. 3l to 4l / 2nd jug to 1st jug79    node.append(min(a_max, a + b))80    node.append(b - (node[0] - a))  # b - ( a' - a)81    if not been_there(node, check_dict):82        next_nodes.append(node)83    node = []8485    # 4. 4l to 3l / 1st jug to 2nd jug86    node.append(min(a + b, b_max))87    node.insert(0, a - (node[0] - b))88    if not been_there(node, check_dict):89        next_nodes.append(node)90    node = []9192    # 5. Empty 4l/ 1st jug93    node.append(0)94    node.append(b)95    if not been_there(node, check_dict):96        next_nodes.append(node)97    node = []9899    # 6. Empty 3l/ 2nd jug100    node.append(a)101    node.append(0)102    if not been_there(node, check_dict):103        next_nodes.append(node)104105106    # Neighbour paths107    for i in range(0, len(next_nodes)):108        temp = list(path)109        temp.append(next_nodes[i])110        result.append(temp)111112    if len(next_nodes) == 0:113        print("No unvisited nodes\n\nTurn back")114    else:115        print("Possible states: ")116        for nnode in next_nodes:117            print(nnode)118119    return result120121122def transition(old, new, jugs):123    124    a = old[0]125    b = old[1]126    a_prime = new[0]127    b_prime = new[1]128    a_max = jugs[0]129    b_max = jugs[1]130131    if a > a_prime:132        if b == b_prime:133            return "Clear {0}-liter jug:\t\t".format(a_max)134        else:135            return "Pour {0}-liter jug into {1}-liter jug:\t".format(a_max, b_max)136    else:137        if b > b_prime:138            if a == a_prime:139                return "Clear {0}-liter jug:\t\t".format(b_max)140            else:141                return "Pour {0}-liter jug into {1}-liter jug:\t".format(b_max, a_max)142        else:143            if a == a_prime:144                return "Fill {0}-liter jug:\t\t".format(b_max)145            else:146                return "Fill {0}-liter jug:\t\t".format(a_max)147148149def print_path(path, jugs):150  151    print("Start State :", path[0])152    for i in  range(0, len(path) - 1):153        print(i+1,":", transition(path[i], path[i+1], jugs), path[i+1])154155156157158##########159160def search(start_node, jugs, target_capacity, check_dict):161    162    target = []163    accomplished = False164    165    q = collections.deque()166    q.appendleft(start_node)167    168    while len(q) != 0:169        path = q.popleft()170        check_dict[get_index(path[-1])] = True171        if len(path) >= 2:172            print(transition(path[-2], path[-1], jugs), path[-1])173        if is_target(path, target_capacity):174            accomplished = True175            target = path176            break177178        next_moves = next_transitions(jugs, path, check_dict)179        for i in next_moves:180                q.append(i)181182    if accomplished:183        print("\nReached to the Target capacity : Sequence")184        print_path(target, jugs)185    else:186        print("Can't find a solution.")187188189if __name__ == '__main__':
...eventType.py
Source:eventType.py  
1# encoding: UTF-82'''3æ¬æä»¶ä»
ç¨äºåæ¾å¯¹äºäºä»¶ç±»å常éçå®ä¹ã4ç±äºpythonä¸ä¸åå¨çæ£çå¸¸éæ¦å¿µï¼å æ¤éæ©ä½¿ç¨å
¨å¤§åçåé忥代æ¿å¸¸éã5è¿é设计çå½åè§å以EVENT_åç¼å¼å¤´ã6常éçå
容é叏鿩ä¸ä¸ªè½å¤ä»£è¡¨ç宿ä¹çå符串ï¼ä¾¿äºçè§£ï¼ã7å»ºè®®å°ææç常éå®ä¹æ¾å¨è¯¥æä»¶ä¸ï¼ä¾¿äºæ£æ¥æ¯å¦åå¨éå¤çç°è±¡ã8'''9EVENT_TIMER = 'eTimer'                  # 计æ¶å¨äºä»¶ï¼æ¯é1ç§åé䏿¬¡10#----------------------------------------------------------------------11def test():12    """æ£æ¥æ¯å¦åå¨å
容éå¤ç常éå®ä¹"""13    check_dict = {}14    15    global_dict = globals()    16    17    for key, value in global_dict.items():18        if '__' not in key:                       # 䏿£æ¥pythonå
置对象19            if value in check_dict:20                check_dict[value].append(key)21            else:22                check_dict[value] = [key]23            24    for key, value in check_dict.items():25        if len(value)>1:26            print(u'åå¨éå¤ç常éå®ä¹:' + str(key) )27            for name in value:28                print(name)29        30    print( u'æµè¯å®æ¯')31    32# ç´æ¥è¿è¡èæ¬å¯ä»¥è¿è¡æµè¯33if __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!!
