Best Python code snippet using avocado_python
My_BypassTree.py
Source:My_BypassTree.py  
1class BSTNode:2    def __init__(self, key, val, parent):3        self.NodeKey = key  # клÑÑ Ñзла4        self.NodeValue = val  # знаÑение в Ñзле5        self.Parent = parent  # ÑодиÑÐµÐ»Ñ Ð¸Ð»Ð¸ None Ð´Ð»Ñ ÐºÐ¾ÑнÑ6        self.LeftChild = None  # левÑй поÑомок7        self.RightChild = None  # пÑавÑй поÑомок8        self.from_level = 09class BSTFind:  # пÑомежÑÑоÑнÑй ÑезÑлÑÑÐ°Ñ Ð¿Ð¾Ð¸Ñка10    def __init__(self):11        self.Node = None  # None еÑли12        # в деÑеве вообÑе неÑÑ Ñзлов13        self.NodeHasKey = False  # True еÑли Ñзел найден14        self.ToLeft = False  # True, еÑли ÑодиÑелÑÑÐºÐ¾Ð¼Ñ ÑÐ·Ð»Ñ Ð½Ð°Ð´Ð¾15                             # добавиÑÑ Ð½Ð¾Ð²Ñй Ñзел левÑм поÑомком16class BST:17    def __init__(self, node=None):18        self.Root = node  # коÑÐµÐ½Ñ Ð´ÐµÑева, или None19        self.levels = 020    def FindNodeByKey(self, key):21        # иÑем в деÑеве Ñзел и ÑопÑÑÑÑвÑÑÑÑÑ Ð¸Ð½ÑоÑмаÑÐ¸Ñ Ð¿Ð¾ клÑÑÑ22        # возвÑаÑÐ°ÐµÑ BSTFind23        itemFind = BSTFind()24        if self.Root == None:25            return itemFind26        else:27            def find(node, key):28                if node.NodeKey < key and node.RightChild != None:29                    find(node.RightChild, key)30                elif node.NodeKey < key and node.RightChild == None:31                    itemFind.Node = node32                    itemFind.NodeHasKey = False33                    itemFind.ToLeft = False34                    return itemFind35                elif node.NodeKey > key and node.LeftChild != None:36                    find(node.LeftChild, key)37                elif node.NodeKey > key and node.LeftChild == None:38                    itemFind.Node = node39                    itemFind.NodeHasKey = False40                    itemFind.ToLeft = True41                    return itemFind42                else:43                    itemFind.Node = node44                    itemFind.NodeHasKey = True45                    return itemFind46                return itemFind47            return find(self.Root, key)48    def AddKeyValue(self, key, val):49        # добавлÑем клÑÑ-знаÑение в деÑево50        # false еÑли клÑÑ Ñже еÑÑÑ51        search_result = self.FindNodeByKey(key)52        if self.Root == None:53            newNode = BSTNode(key, val, None)54            self.Root = newNode55            newNode.from_level = 156            return True57        elif search_result.NodeHasKey == True:58            return False59        elif search_result.NodeHasKey == False:60            if search_result.ToLeft == True:61                newNode = BSTNode(key, val, search_result.Node)62                search_result.Node.LeftChild = newNode63                newNode.Parent = search_result.Node64                newNode.from_level = self.Count_Parent(newNode)65                return True66            else:67                newNode = BSTNode(key, val, search_result.Node)68                search_result.Node.RightChild = newNode69                newNode.Parent = search_result.Node70                newNode.from_level = self.Count_Parent(newNode)71                return True72    def FinMinMax(self, FromNode, FindMax=False):73        # иÑем макÑималÑное/минималÑное (Ñзел) в поддеÑеве74        if self.Root == None or FromNode == None:75            return None76        node = FromNode77        if FindMax == False:78            while node.LeftChild != None:79                node = node.LeftChild80            return node81        else:82            while node.RightChild != None:83                node = node.RightChild84            return node85    def DeleteNodeByKey(self, key):86        # ÑдалÑем Ñзел по клÑÑÑ ÐµÑли Ñзел не найден87        if self.Root == None:88            return False89        else:90            def remove_leaf(del_node):91                # ÑÑнкÑÐ¸Ñ ÑÐ´Ð°Ð»ÐµÐ½Ð¸Ñ Ð»Ð¸ÑÑа92                if del_node.Parent.LeftChild == del_node:93                    del_node.Parent.LeftChild = None94                    del_node.Parent = None95                else:96                    del_node.Parent.RightChild = None97                    del_node.Parent = None98                return True99            100            def remove_node_with_right_child(del_node):101                # ÑÑнкÑÐ¸Ñ ÑÐ´Ð°Ð»ÐµÐ½Ð¸Ñ Ñзла Ñ Ð¾Ð´Ð½Ð¸Ð¼ пÑавÑм поÑомком102                if del_node.Parent.LeftChild == del_node:103                    del_node.Parent.LeftChild = del_node.RightChild104                else:105                    del_node.Parent.RightChild = del_node.RightChild106                del_node.RightChild.Parent = del_node.Parent107                del_node.Parent = None108                del_node.RightChild = None109                return True110            111            def remove_node_with_left_child(del_node):112                # ÑÑнкÑÐ¸Ñ ÑÐ´Ð°Ð»ÐµÐ½Ð¸Ñ Ñзла Ñ Ð¾Ð´Ð½Ð¸Ð¼ левÑм поÑомком113                if del_node.Parent.LeftChild == del_node:114                    del_node.Parent.LeftChild = del_node.LeftChild115                else:116                    del_node.Parent.RightChild = del_node.LeftChild117                del_node.LeftChild.Parent = del_node.Parent118                del_node.Parent = None119                del_node.LeftChild = None120                return True121            122            find_remove = self.FindNodeByKey(key)123            del_node = find_remove.Node124            if find_remove.NodeHasKey == False:125                return False126            elif del_node.Parent == None: # еÑли ÑдалÑемÑй Ñзел - коÑенÑ127                self.Root = None128                return True129            elif del_node.RightChild == None and del_node.LeftChild == None:130                # еÑли в ÑдалÑемом Ñзле Ð½ÐµÑ Ð¿Ð¾Ñомков131                return remove_leaf(del_node)132            elif (del_node.RightChild != None and del_node.LeftChild == None):133                # еÑли в ÑдалÑемом Ñзле еÑÑÑ Ð¾Ð´Ð¸Ð½ пÑавÑй поÑомок134                return remove_node_with_right_child(del_node)135            elif (del_node.RightChild == None and del_node.LeftChild != None):136                # еÑли в ÑдалÑемом Ñзле еÑÑÑ Ð¾Ð´Ð¸Ð½ левÑй поÑомок137                return remove_node_with_left_child(del_node)138            elif (del_node.RightChild != None and del_node.LeftChild != None):139                # еÑли в ÑдалÑемом Ñзле еÑÑÑ Ð¾Ð±Ð° поÑомка140                node = del_node.RightChild141                while True:142                    if (node.LeftChild == None and node.RightChild != None): # наÑли Ñзел ÑолÑко Ñ Ð¿ÑавÑм поÑомком. ÐоÑомка пеÑемеÑаем на меÑÑо ÑдалÑемого143                        del_node.NodeKey = node.NodeKey144                        del_node.NodeValue = node.NodeValue145                        return remove_node_with_right_child(node)146                    elif (node.LeftChild == None and node.RightChild == None):  # наÑли лиÑÑ. Ðго помеÑаем на меÑÑо ÑдалÑемого Ñзла.147                        del_node.NodeKey = node.NodeKey148                        del_node.NodeValue = node.NodeValue149                        return remove_leaf(node)150                    node = node.LeftChild151    def Count_Parent(self, node):152        count = 1153        while node.Parent != None:154            node = node.Parent155            count += 1156        return count157    def Count(self):158        # колиÑеÑÑво Ñзлов в деÑеве159        list_count = []160        if self.Root == None:161            return 0162        else:163            def find(node):164                list_count.append(1)165                if node.RightChild != None and node.LeftChild != None:166                    child = []167                    child.append(node.LeftChild)168                    child.append(node.RightChild)169                    for i in child:170                        find(i)171                elif node.RightChild != None and node.LeftChild == None:172                    find(node.RightChild)173                elif node.RightChild == None and node.LeftChild != None:174                    find(node.LeftChild)175                elif node.RightChild == None and node.LeftChild == None:176                    return list_count177                return list_count178            size = len(find(self.Root))179            return size180    def  WideAllNodes(self):181        q = []182        list_all = []183        if self.Root == None:184            return list_all185        else:186            q.append(self.Root)187            while len(q) != 0:188                node = q.pop(0)189                list_all.append(node)190                if node.LeftChild != None:191                    q.append(node.LeftChild)192                if node.RightChild != None:193                    q.append(node.RightChild)194            return list_all195    def DeepAllNodes(self, option_bypass):196        list_all = []197        if self.Root == None:198            return list_all199        else:200            def bypass_0(node, list_all):201                if node.LeftChild != None and node.RightChild != None:202                    bypass_0(node.LeftChild, list_all)203                    list_all.append(node)204                    bypass_0(node.RightChild, list_all)205                    return list_all206                elif node.LeftChild == None and node.RightChild != None:207                    list_all.append(node)208                    bypass_0(node.RightChild, list_all)209                    return list_all210                elif node.LeftChild != None and node.RightChild == None:211                    bypass_0(node.LeftChild, list_all)212                    return list_all213                else:214                    list_all.append(node)215                    return list_all216            def bypass_1(node, list_all):217                if node.LeftChild != None and node.RightChild != None:218                    bypass_1(node.LeftChild, list_all)219                    bypass_1(node.RightChild, list_all)220                    list_all.append(node)221                    return list_all222                elif node.LeftChild == None and node.RightChild != None:223                    bypass_1(node.RightChild, list_all)224                    list_all.append(node)225                    return list_all226                elif node.LeftChild != None and node.RightChild == None:227                    bypass_1(node.LeftChild, list_all)228                    list_all.append(node)229                    return list_all230                else:231                    list_all.append(node)232                    return list_all233                234            def bypass_2(node, list_all):235                if node.LeftChild != None and node.RightChild != None:236                    list_all.append(node)237                    bypass_2(node.LeftChild, list_all)238                    bypass_2(node.RightChild, list_all)239                    return list_all240                elif node.LeftChild == None and node.RightChild != None:241                    list_all.append(node)242                    bypass_2(node.RightChild, list_all)243                    return list_all244                elif node.LeftChild != None and node.RightChild == None:245                    list_all.append(node)246                    bypass_2(node.LeftChild, list_all)247                    return list_all248                else:249                    list_all.append(node)250                    return list_all251            if option_bypass == 0:252                bypass_0(self.Root, list_all)253                return list_all254            elif option_bypass == 1:255                bypass_1(self.Root, list_all)256                return list_all257            elif option_bypass == 2:258                bypass_2(self.Root, list_all)259                return list_all260"""261My_BTS = BST()262My_BTS.AddKeyValue(70, 7)263My_BTS.AddKeyValue(31, 3)264My_BTS.AddKeyValue(80, 8)265My_BTS.AddKeyValue(22, 2)266My_BTS.AddKeyValue(37, 3)267My_BTS.AddKeyValue(73, 7)268My_BTS.AddKeyValue(91, 7)269My_BTS.AddKeyValue(18, 7)270My_BTS.AddKeyValue(25, 7)271My_BTS.AddKeyValue(100, 7)272My_BTS.AddKeyValue(20, 2)273My_BTS.AddKeyValue(23, 2)274My_BTS.AddKeyValue(27, 2)275My_BTS.AddKeyValue(26, 2)276print('size:', My_BTS.Count())277root = My_BTS.FindNodeByKey(70)278deep = My_BTS.DeepAllNodes(1)279wide = My_BTS.WideAllNodes()280#print(deep, wide)281for i in deep:282    print(i.NodeKey)...main_TimingGeneData.py
Source:main_TimingGeneData.py  
1# -*- coding: utf-8 -*-2"""3Created on Sun May 19 17:34:46 20194@author: 329085"""6import csv7import random8import time 9from datetime import datetime10import pymysql11import uuid12# -----------------------------------------------------------------------------13def strTimeProp(start, end, prop, frmt):14    stime = time.mktime(time.strptime(start, frmt))15    etime = time.mktime(time.strptime(end, frmt))16    ptime = stime + prop * (etime - stime)17    return int(ptime)18def randomDate(start, end, frmt='%Y-%m-%d %H:%M:%S'):19    return time.strftime(frmt, time.localtime(strTimeProp(start, end, random.random(), frmt)))20# -----------------------------------------------------------------------------21def get_column(key,column_all):22    column = [row[key] for row in column_all]23    column = list(set(column))24    return column 25# -----------------------------------------------------------------------------26def gen_uuid():27    uuid_now = str(uuid.uuid4())28    uuid_tmp = uuid_now.split('-')29    uuid_now = "".join(uuid_tmp)30    return uuid_now31# -----------------------------------------------------------------------------32def get_faultobj():33    count = random.randint(0,4)34    list_obj = []35    with open("fault_object_all.csv","r",encoding="utf-8-sig") as csvfile:36        reader = csv.DictReader(csvfile)37        column_all = [row for row in reader]38        if count != 0:39            for i in range(1,count+1):40                column = get_column(str(i),column_all)41                cho = random.choice(column)42                list_obj.append(cho)43            str_obj = ".".join(list_obj)44        else:45            str_obj = ''46        return str_obj47# -----------------------------------------------------------------------------48def write2mysql(list_all):49    db = pymysql.connect("192.168.1.21","root","123456",charset="utf8")50    cur = db.cursor()51    cur.execute("use darams")52    uuid_now = gen_uuid()53    time_now = datetime.now()54    sql = \55    '''56    INSERT INTO data_fault_order_simu VALUES('{}',{},'{}','{}','{}','{}','{}','{}','{}','{}','{}','{}',{},'{}','{}','{}','{}',{},\57    '{}','{}',{},'{}','{}','{}','{}','{}','{}','{}','{}','{}',{},'{}',{},{},'{}','{}','{}','{}','{}','{}','{}','{}','{}','{}',\58    '{}','{}','{}',{},'{}','{}',{},'{}','{}','{}','{}','{}','{}',{},'{}','{}',{},'{}',{},{},{},{},'{}','{}','{}','{}','{}',\59    'YX','{}','YX','{}','0','')60    '''.format(uuid_now,list_all[0],list_all[1],list_all[2],list_all[3],list_all[4],list_all[5],list_all[6],list_all[7],list_all[8],\61    list_all[9],list_all[10],list_all[11],list_all[12],list_all[13],list_all[14],list_all[15],list_all[16],list_all[17],\62    list_all[18],list_all[19],list_all[20],list_all[23],list_all[24],list_all[25],list_all[26],\63    list_all[27],list_all[28],list_all[29],list_all[30],list_all[31],list_all[32],list_all[33],list_all[34],list_all[35],\64    list_all[36],list_all[37],list_all[38],list_all[39],list_all[40],list_all[41],list_all[42],list_all[43],list_all[44],\65    list_all[45],list_all[46],list_all[47],list_all[48],list_all[49],list_all[50],list_all[51],list_all[52],list_all[53],\66    list_all[54],list_all[55],list_all[56],list_all[57],list_all[58],list_all[59],list_all[60],list_all[61],list_all[62],\67    list_all[63],list_all[64],list_all[65],list_all[66],list_all[67],list_all[68],list_all[69],list_all[70],list_all[71],\68    time_now,time_now)69    cur.execute(sql)70    db.commit()71    db.close()72#    print(sql)73# -----------------------------------------------------------------------------74def main(list_keys):75#    count = 176#    if  count >= 1 \77#    and count <= 10:78    list_all = []79    start = '2018-06-02 12:12:12'80    end = '2018-11-01 00:00:00'81    with open("data_template.csv","r",encoding = "utf-8-sig") as csvfile:82        reader = csv.DictReader(csvfile)83        column_all = [row for row in reader]84        for key in list_keys:85            if key in ['if_fault_id','intuitive_fault_object_id','intuitive_fault_pattern_id','accumulated_mileage',\86                       'real_fault_object_id','real_fault_pattern_id','replace_parts']:87                cho = random.randint(1,9999999)88            elif key in ['start_late','end_late','diagnostic_time','debugging_time','total_repair_counts','repair_time',\89                         'total_downtime']:90                cho = random.uniform(0,100)91                cho = round(cho,2)92            elif key == 'fault_no':93                cho = 'simu_' + str(list_all[0])94            elif key == 'train_no':95                continue96            elif key == 'train_type':97                column = get_column(key,column_all)98                cho = random.choice(column)99                cho_split = cho.split(':')100                list_all.append(cho_split[-1])101                cho = cho_split[0]102            elif key in ['occurrence_time','occurrence_time','report_time','processing_date']:103                cho = randomDate(start,end)104            elif key in ['fault_brief','configuration_location','intuitive_fault_object','intuitive_fault_object_desc',\105                         'intuitive_fault_pattern_desc','fault_desc','report_person','report_part','contact_tel',\106                         'real_fault_object','real_other_fault_object_desc','real_other_fault_pattern_desc','fault_cause',\107                         'other_fault_cause_desc','initial_cause_analysis','final_cause_analysis','initial_treatment_measures',\108                         'final_treatment_measures']:109                cho = get_faultobj()110            elif key in ['fault_environment','fault_result','other_solution','closed_loop_time']:111                cho = 'None'112            else:113                column = get_column(key,column_all)114                cho = random.choice(column)115            list_all.append(cho)116#    print(list_all)117#    print(len(list_all))118    write2mysql(list_all)119# -----------------------------------------------------------------------------120# if __name__ == "__main__":121#     list_keys = ['if_fault_id', 'fault_no', 'status', 'occurrence_time', 'occurrence_place', 'train_no', 'train_type', 'car_no', 'railway', 'report_position', 'cause_class', 'org_id', 'fault_level', 'fault_brief', 'configuration_location', 'intuitive_fault_object', 'intuitive_fault_object_id', 'intuitive_fault_object_desc', 'intuitive_fault_pattern', 'intuitive_fault_pattern_id', 'intuitive_fault_pattern_desc', 'reconnect_location', 'occurrence_time', 'occurrence_place', 'accident_level', 'responsibility_class', 'running_way', 'fault_environment', 'main_responsibility', 'other_responsibility', 'car_trips', 'accumulated_mileage', 'fault_result', 'start_late', 'end_late', 'fault_desc', 'fault_order_type', 'report_time', 'processing_date', 'processing_result', 'special_fault', 'safety_supervisio_fault', 'in_repair', 'startup_fault_analysis', 'report_person', 'report_part', 'contact_tel', 'real_fault_object', 'real_fault_object_id', 'real_other_fault_object_desc', 'real_fault_pattern', 'real_fault_pattern_id', 'real_other_fault_pattern_desc', 'fault_cause', 'other_fault_cause_desc', 'solution', 'other_solution', 'fault_property', 'diagnostic_time', 'initial_cause_analysis', 'final_cause_analysis', 'replace_parts', 'repair_location', 'debugging_time', 'total_repair_counts', 'repair_time', 'total_downtime', 'repair_property', 'initial_treatment_measures', 'final_treatment_measures', 'important_info_no', 'closed_loop_time']122# #    list_keys = ['if_fault_id','fault_no','status','occurrence_time','train_no','train_type','intuitive_fault_object']123#     main(list_keys)...utils.py
Source:utils.py  
1import pandas as pd2import glob3from datetime import datetime, timedelta4# read all csv in folder 'dataset'5def read_csv():6    list_csv = []7    name_path = 'dataset'8    # Select all csv in folder selected9    names_files = glob.glob(name_path + "/*.csv")10    # join all them11    for filename in names_files:12        df = pd.read_csv(filename, sep=';')13        df_mask = df['codmun'].isnull()14        filtered_df = df[df_mask]15        list_csv.append(filtered_df)16    frame = pd.concat(list_csv, axis=0, ignore_index=True)17    frame['data'] = pd.to_datetime(frame['data'])  # .dt.strftime('%d/%m/%Y')18    return frame19# Calculate all itens20def itens_calculate(df, date, date_start, uf):21    list_all = []22    mask = df['data'] == date.strftime('%Y-%m-%d')23    df_aux = df[mask]24    # Date25    list_all.append(date)26    # State27    if uf == 76:28        list_all.append('Brasil')29    else:30        list_all.append(df['estado'].iloc[0])31    # CasosAcumulado32    list_all.append(int(df_aux['casosAcumulado'].iloc[0]))33    # MediaMovelCasosAtual, MediaMovelCasosAnterior, Situação, Porcentagem34    for i in moving_average(df, date, date_start, 0):35        list_all.append(i)36    # ObitosAcumulados37    list_all.append(df_aux['obitosAcumulado'].iloc[0])38    # MediaMovelObtitosAtual, MediaMovelObitosAnterior, Situação, Porcentagem39    for j in moving_average(df, date, date_start, 1):40        list_all.append(j)41    return list_all42# number = 0 -> Casos or number != 0 -> Ãbitos43def moving_average(df, date, date_start, number):44    list_all = []45    if number == 0:46        df_aux = df[['data', 'casosAcumulado']]47    else:48        df_aux = df[['data', 'obitosAcumulado']]49    # MediaMovelAtual50    mean_today = average_call(df, date, date_start, number)51    # MediaMovelAnterior52    mean_before = average_call(53        df, date - timedelta(days=1), date_start, number)54    list_all.append(int(mean_today))55    list_all.append(int(mean_before))56    # Situação e Porcentagem of each moving-average57    if mean_before == 0:58        if mean_today != 0:59            list_all.append('Aumento')60            list_all.append(100)61        else:62            list_all.append('Estabilidade')63            list_all.append('-')64    elif mean_today/mean_before > 1:65        list_all.append('Aumento')66        list_all.append(round(((mean_today/mean_before - 1)*100), 4))67    elif mean_today/mean_before < 1:68        list_all.append('Diminuicao')69        list_all.append(round(abs(mean_today/mean_before - 1)*100, 4))70    else:71        list_all.append('Estabilidade')72        list_all.append(round((mean_today/mean_before - 1)*100, 4))73    return list_all74# Calculate Average Moving75def average_call(df, date, date_start, number):76    colum = ''77    if number == 0:78        colum = 'casosAcumulado'79    else:80        colum = 'obitosAcumulado'81    # First 7 days82    if date.strftime('%Y-%m-%d') < (date_start + timedelta(days=7)).strftime('%Y-%m-%d'):83        mask = (df['data'] <= date.strftime('%Y-%m-%d'))84        df_aux = df[mask]85        return df_aux[colum].sum()/786    # After87    else:88        # Select part of dataframe that need to calculate mean89        mask = (df['data'] <= date.strftime(90            '%Y-%m-%d')) & (df['data'] > (date - timedelta(days=7)).strftime('%Y-%m-%d'))91        df_aux = df[mask]...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!!
