Best Python code snippet using avocado_python
exp2..py
Source:exp2..py
1# from typing_extensions import ParamSpec2import numpy as np3import matplotlib.pyplot as plt4from mpl_toolkits.mplot3d import Axes3D5 6def dist(v_A, v_B):7 """8 å¤æ两个èç¹ä¹é´çä¸ç»´è·ç¦»9 :param v_A: A äºç»´åé10 :param v_B: B äºç»´åé11 :return: ä¸ç»´è·ç¦»12 """13 return np.sqrt(np.power((v_A[0] - v_B[0]), 2) + np.power((v_A[1] - v_B[1]), 2))14 15def node_factory(N, R, r, energy=50):16 """17 çæN个èç¹çææç½ç»18 :param N: ç½ç»ä¸èç¹ä¸ªæ°19 :param R: åå½¢ææåå¾20 :para r: éä¿¡åå¾èå´ï¼è¶
åºæ¤èå´ä¸ºæç°çå¤ç«èç¹21 :param selected_flag: æ å¿:æ¯å¦è¢«éæ©ä¸ºç°é¦-->åå§å为022 :param energy: è½é23 :return: èç¹éånodes=[[x,y,e],[x,y,e]...]24 """25 nodes = []26 selected_flag = []27 iso = []28 # ä¸å¿sinkèç¹29 sinknode = [0, 0, energy]30 nodes.append(sinknode)31 selected_flag.append(0)32 33 # éæºçæåå½¢ææç½ç»34 i = 035 while i < N-1:36 # å¨1*1ç©éµçæ[x,y]åæ 37 node = [np.random.uniform(-1, 1)*R, np.random.uniform(-1, 1)*R, energy]38 if dist(node, sinknode) < R and dist(node, sinknode) > r:39 nodes.append(node)40 selected_flag.append(0)41 iso.append(1)42 i = i + 143 elif dist(node, sinknode) < R and dist(node, sinknode) < r:44 nodes.append(node)45 selected_flag.append(0)46 iso.append(0)47 i = i + 148 49 return nodes, selected_flag, iso50 51 52def sel_heads(r, nodes, flags):53 """54 使ç¨leachåè®®ï¼éåç°å¤´ï¼æ³¨æè¿éè¿æ²¡æå¼å§è¿å
¥æ£å¼çåç°ï¼è¿éåªéäºç°å¤´ï¼55 :param r: è½®æ°56 :param nodes: èç¹å表57 :param flags: éæ©æ å¿58 :param P: æ¯ä¾å å59 :return: ç°é¦å表heads,ç°æåå表members60 """61 # éå¼å½æ° Tn 使ç¨leach计ç®62 P = 0.25 * (200 / len(nodes))63 Tn = P / (1 - P * (r % (1 / P)))64 heads = [] # ç°é¦å表65 members = [] # ç°æåå表66 n_head = 0 # æ¬è½®ç°é¦æ°67 rands = [np.random.random() for _ in range(len(nodes))] # 对æ¯ä¸ªèç¹çæ对åºçéæºæ°ï¼ç¨äºçéç°å¤´68 69 # éåéæºæ°å表ï¼éåç°é¦70 for i in range(len(nodes)):71 # éæºæ°ä½äºéå¼-->é为ç°é¦72 if rands[i] <= Tn:73 flags[i] = 174 heads.append(nodes[i])75 n_head += 176 # éæºæ°é«äºéå¼77 else:78 members.append(nodes[i])79 80 return heads, members81 82 83def classify(nodes, flag, r, mode=1, k=20):84 """85 对ç½ç»è¿è¡ç°åç±»86 :param nodes: èç¹å表87 :param flag: èç¹æ è®°88 :param mode: 0-->æ¾ç¤ºå¾ç(æ»äº¡èç¹ä¸æ¾ç¤º) 1-->æ¾ç¤ºç»æè½®æ°89 :param k: è½®æ°90 :return: ç°åç±»ç»æå表 classes[[ç±»1..],[ç±»2...],......] [ç±»1...ç°é¦...ç°æå]91 """92 # è½éæè模åçåæ°93 b = 2400 # æ¯ç¹æ°94 e_elec = 5*np.power(10., -9)*10095 e_fs = 10*np.power(10., -12)*10096 e_mp = 0.0013*np.power(10., -12)*10097 d_0 = 4.0 # éå¼98 # kè½®çææéå: æ æ»äº¡èç¹99 iter_classes = []100 # æ¯å¦å·²æèç¹è½é为0101 e_is_empty = 0102 103 # è¿ä»£rè½®104 for r in range(k):105 # mode1: è¥æ æ»äº¡èç¹ ç»§ç»è¿ä»£106 if e_is_empty == 0:107 # è·åç°é¦å表ï¼ç°æåå表108 heads, members = sel_heads(r,nodes,flag)109 110 # 建ç«ç°ç±»çå表111 if len(heads) == 0:112 break113 classes = [[] for _ in range(len(heads))]114 115 # å°ç°é¦ä½ä¸ºé¦èç¹æ·»å å°èç±»å表ä¸116 for i in range(len(heads)):117 classes[i].append(heads[i])118 119 # ç°åç±»:éåèç¹node120 for member in members:121 122 # éåè·ç¦»æå°çèç¹123 dist_min = 100000124 125 # å¤æåæ¯ä¸ªç°é¦çè·ç¦»126 for i in range(len(heads)):127 128 dist_heads = dist(member, heads[i])129 130 # æ¾å°è·ç¦»æå°çç°å¤´å¯¹åºçheadsä¸æ i131 if dist_heads < dist_min:132 dist_min = dist_heads133 head_cla = i134 if dist_min==1:135 print("æ¬è½®æ²¡æç°é¦!")136 break137 # æ·»å å°è·ç¦»æå°çç°é¦å¯¹åºçèç±»å表ä¸138 classes[head_cla].append(member)139 140 # æ£å¼çæ°æ®ä¼ è¾è¿ç¨ï¼ä½¿ç¨è½éæ¶è模å141 if int(member[2]) > 0 and int(heads[head_cla][2]) > 0:142 if dist_min < d_0:143 member[2] -= e_elec*b+e_fs*b*dist_min144 else:145 member[2] -= e_elec*b+e_mp*b*dist_min146 147 if dist([member[0], member[1]], [heads[head_cla][0], heads[head_cla][1]]) <= r:148 heads[head_cla][2] -= e_elec*b149 else:150 pass151 # heads[head_cla][2] -= e_elec*b152 else:153 e_is_empty = mode154 # break155 iter_classes.append(classes)156 157 else:158 print("第", r, "è½®è½éèå°½")159 break160 161 return iter_classes162 163 164def show_plt(classes, R, r):165 """166 æ¾ç¤ºåç±»å¾167 :param classes: [[ç±»1...],[ç±»2...]....]-->[ç°é¦,æå,æå...]168 :param R: åå½¢ææåå¾169 :para r: éä¿¡åå¾èå´ï¼è¶
åºæ¤èå´ä¸ºæç°çå¤ç«èç¹170 :return:171 """172 fig = plt.figure()173 ax1 = plt.gca()174 175 # 设置æ é¢176 ax1.set_title('WSN2')177 # 设置Xè½´æ ç¾178 plt.xlabel('X')179 # 设置Yè½´æ ç¾180 plt.ylabel('Y')181 182 # ç°å
çæ¾ç¤ºç¹å¾æ åè¿çº¿é¢è²ï¼ä»¥å¾å°è¾å¥½çæ¾ç¤ºç»æ183 icon = ['o', '*', '.', 'x', '+', 's']184 color = ['b', 'g', 'c', 'y', 'm']185 186 x, y, e = [], [], []187 # 对ä¸åçç°è¿è¡ä¸åçæ¾ç¤ºï¼ä»¥å¾å°è¾å¥½çæ¾ç¤ºç»æ188 for i in range(len(classes)):189 centor = classes[i][0]190 x.append(centor[0])191 y.append(centor[1])192 e.append(centor[2])193 for point in classes[i]:194 if point[2] > 0 and dist(centor, point) < r:195 ax1.plot([centor[0], point[0]], [centor[1], point[1]], c=color[i % 5], marker=icon[i % 5], alpha=0.4)196 elif point[2] > 0 and dist(centor, point) > r:197 ax1.plot([centor[0], point[0]], [centor[1], point[1]], c='r', marker=icon[i % 5], alpha=0.4)198 else:199 pass200 a, b = (0., 0.)201 theta = np.arange(0, 2*np.pi, 0.01)202 x = a + R * np.cos(theta)203 y = b + R * np.sin(theta)204 plt.plot(x, y, 'y')205 # æ¾ç¤º206 plt.show()207 208def show_eninfo(iter_classes):209 fig = plt.figure()210 ax1 = Axes3D(fig)211 lastclass = iter_classes[-1]212 x, y, e = [], [], []213 # å°ææèç¹çå©ä½è½éç»è®¡èµ·æ¥ï¼ç¨äºåç»è½éä¸ç»´å¾çæ¾ç¤º214 for i in range(len(lastclass)):215 for point in lastclass[i]:216 x.append(point[0])217 y.append(point[1])218 e.append(point[2])219 # éè¦è¿è¡æ°æ®ç±»å转æ¢list->ndarrayï¼æè½è¿è¡ä¸ç»´å¾åçæ¾ç¤º220 x = np.array(x)221 y = np.array(y)222 e = np.array(e)223 # æ¾ç¤ºä¸ç»´å¾å224 print(f"åèç¹è½éçæ åå·®: {np.std(e):.4f}")225 ax1.plot_trisurf(x, y, e, cmap='rainbow')226 plt.show()227def run():228 """229 1ãè¾å
¥èç¹ä¸ªæ°N230 2ãnode_factory(N,energy): çæN个èç¹çå表ï¼èç¹çè½éåå§å为energy231 3ãclassify(nodes,mode=1,k=100): è¿è¡ç°åç±»ï¼è¿åææç°çå表232 mode=0: å½èç¹æ»äº¡ä¸åæ¢ï¼è¿è¡k次è¿ä»£ï¼æ¾ç¤ºkå¼ å¾ï¼å¾ä¸å·²æ»äº¡èç¹ä¸æ è®°233 mode=1: å½èç¹æ»äº¡åæ¢ï¼è®°å½ç¬¬ä¸ä¸ªèç¹æ»äº¡æ¶çè½®æ°ï¼æ¾ç¤ºæ æ»äº¡èç¹çå¾234 4ãshow_plt(classes): è¿ä»£æ¯æ¬¡èç±»ç»æï¼æ¾ç¤ºè¿çº¿å¾235 :return:236 """237 # N = int(input("请è¾å
¥èç¹ä¸ªæ°:"))238 N = 300239 R = 20240 r = 5241 # è·ååå§èç¹å表242 nodes, flag, iso = node_factory(N, R, r, energy=5)243 # 对èç¹å表è¿è¡ç°åç±»,modeä¸ºæ¨¡å¼ 2ç§244 iter_classes = classify(nodes,flag, r, mode=1, k=200)245 # è¿ä»£æ¯æ¬¡èç±»ç»æï¼æ¾ç¤ºè¿çº¿å¾246 for classes in iter_classes:247 # æ¾ç¤ºåç±»ç»æ248 show_plt(classes, R, r)249 show_eninfo(iter_classes)250if __name__ == '__main__':...
clustering.py
Source:clustering.py
1'''2 * @Author: zhikunch 3 * @Date: 2021-03-19 20:39:28 4 * @Last Modified by: zhikunch5 * @Last Modified time: 2021-03-19 20:43:396 '''7 # devide users into several clusters following leach protocal8import numpy as np9import matplotlib.pyplot as plt10def dist(v_A, v_B):11 """12 å¤æ两个èç¹ä¹é´çè·ç¦»13 :param v_A: A äºç»´åé14 :param v_B: B äºç»´åé15 :return: è·ç¦»16 """17 return np.sqrt(np.power((v_A[0] - v_B[0]), 2) + np.power((v_A[1] - v_B[1]), 2))18def node_factory(N):19 """20 çæN个èç¹çéå21 :param N:èç¹çæ°ç®22 :param nodes: èç¹çéå23 :param selected_flag: æ å¿ï¼æ¯å¦è¢«éæ©ä¸ºç°é¦-->åå§å为024 :return: èç¹éånodes=[[x,y],[x,y]...] + æ å¿ flag25 """26 nodes = []27 selected_flag = []28 for i in range(0, N):29 # 1*1çæ[x,y]åæ 30 node = [np.random.random(),np.random.random()]31 # print("çæçèç¹ä¸ºï¼",node)32 nodes.append(node)33 # åå§å对åºæ å¿ä¸º034 selected_flag.append(0)35 return nodes, selected_flag36def sel_heads(r, nodes, flags):37 """38 æ ¹æ®éå¼éåç°å¤´èç¹39 ï¼param r: è½®æ°40 ï¼param nodesï¼èç¹å表41 ï¼param flagsï¼éæ©æ å¿42 ï¼param Pï¼æ¯ä¾å å43 ï¼returnï¼ç°é¦å表headsï¼ç°æåå表members44 """45 # éå¼å½æ°Tn使ç¨leach计ç®46 P = 0.1 * (100 / len(nodes))47 Tn = P / (1 - P * (r % (1/P)))48 49 # ç°é¦å表50 heads = []51 # æåå表52 members = []53 # æ¬è½®ç°é¦æ°54 n_head = 055 56 # 对æ¯ä¸ªèç¹çæ对åºçéæºæ°57 rands = [np.random.random() for _ in range(len(nodes))]58 59 # éåéæºæ°å表ï¼éåç°é¦60 for i in range(len(nodes)):61 # è¥æ¤èç¹æªè¢«éæ©ä¸ºç°é¦62 if flags[i] == 0:63 # éæºæ°ä½äºéå¼-->é为ç°é¦64 if rands[i] <= Tn:65 flags[i] = 166 heads.append(nodes[i])67 n_head += 168 # éæºæ°é«äºéå¼69 else:70 members.append(nodes[i])71 # è¥æ¤èç¹å·²ç»è¢«éæ©è¿72 else:73 members.append(nodes[i])74 75# print("ç°é¦ä¸ºï¼", len(heads),"个")76# print("ç°æå为ï¼",len(members),"个")77 78 return heads, members79def classify(nodes, flag, k=1):80 """81 è¿è¡ç°åç±»82 ï¼param nodesï¼èç¹å表83 ï¼param flagï¼èç¹æ è®°84 ï¼param kï¼è½®æ°85 ï¼returnï¼ç°åç±»ç»æå表 classes[[ç±»1..],[ç±»2..],......] [ç±»1...ç°é¦...ç°æå]86 """87 # kè½®çéå88 global head_cla89 iter_classes = []90 # è¿ä»£rè½®91 for r in range(k):92 # è·åç°é¦å表ï¼ç°æåå表93 heads, members = sel_heads(r, nodes, flag)94 95 # 建ç«ç°ç±»çå表96 classes = [[] for _ in range(len(heads))]97 98 # å°ç°é¦ä½ä¸ºé¦èç¹æ·»å å°èç±»å表ä¸99 for i in range(len(heads)):100 classes[i].append(heads[i])101 ch = np.argwhere(np.array(nodes) == heads[i])[0][0]102 print("head:",ch)103 # ç°åç±»ï¼éåèç¹node104 for n in range(len(members)):105 # éåè·ç¦»æå°çèç¹106 dist_min = 1107 108 for i in range(len(heads)):109 dist_heads = dist(members[n], heads[i])110 111 # æ¾å°è·ç¦»æå°çç°å¤´å¯¹åºçheadsä¸æ i112 if dist_heads < dist_min:113 dist_min = dist_heads114 head_cla = i115 # 0 个ç°é¦çæ
åµ116 if dist_min == 1:117 print("æ¬è½®æ²¡æç°é¦ï¼")118 break119 # æ·»å å°è·ç¦»æå°çç°é¦å¯¹åºçèç±»å表ä¸120 classes[head_cla].append(members[n])121 122 iter_classes.append(classes)123 # dict124 dict_clusters = {j:{} for j in range(len(iter_classes[0]))}125 for j in range(len(iter_classes[0])):126 # print(len(iter_classes[0][j]))127 idx = []128 for jj in range(len(iter_classes[0][j])):129 idx.append(np.argwhere(np.array(nodes)==iter_classes[0][j][jj])[0][0])130 dict_clusters[j] = idx131 return iter_classes, dict_clusters132def show_plt(classes):133 """134 æ¾ç¤ºåç±»å¾135 ï¼param classesï¼[[ç±»1..],[ç±»2..],....]-->[ç°é¦ï¼æåï¼æå...]136 : return: 137 """138 fig = plt.figure()139 ax1 = plt.gca()140 141 ax1.set_title('WSN1')142 plt.xlabel('X')143 plt.ylabel('Y')144 145 icon = ['o','*','.','x','+','s']146 color = ['r','b','g','c','y','m']147 148 # 对æ¯ä¸ªç°åç±»å表è¿è¡show149 for i in range(len(classes)):150 centor = classes[i][0]151 for point in classes[i]:152 ax1.plot([centor[0],point[0]],[centor[1],point[1]], c=color[i % 6], marker=icon[i % 5],alpha=0.4)153 plt.show()154def run_leach(cluster_num):155 """156 1ãè¾å
¥èç¹æ°N157 2ãnode_factory(N)ï¼çæN个èç¹çå表158 3ãclassify(nodes, flags, k=10):è¿è¡kè½®ç°åç±»ï¼flagæ è®°çèç¹ä¸åæ为ç°é¦ï¼è¿åææç°159 4ãshow_plt(classes):è¿ä»£æ¯æ¬¡èç±»ç»æï¼æ¾ç¤ºè¿çº¿å¾160 returnï¼161 """162 N=100163 # è·ååå§èç¹å表ï¼éæ©æ å¿å表164 nodes, flags = node_factory(N)165 # 对èç¹å表è¿è¡ç°åç±»ï¼k为è¿ä»£è½®æ°166 iter_classes, dict_clusters = classify(nodes, flags, k=1)167 168 # for classes in iter_classes:169 # show_plt(classes)170 return dict_clusters171if __name__ == '__main__':172 clusters = run_leach()173 # print(len(classes[0]))...
jarjar
Source:jarjar
...6parser = argparse.ArgumentParser(description='jarjar')7parser.add_argument("jarsa")8parser.add_argument("jarsb")9args = parser.parse_args()10def iter_classes(jarname, jar):11 with zipfile.ZipFile(jar, 'r') as zip:12 for name in zip.namelist():13 if name.endswith('.class'):14 yield jarname, name15def iter_jars(top):16 if os.path.isdir(top):17 for root, dirs, files in os.walk(top):18 for name in files:19 if name.endswith(".jar"):20 yield from iter_classes(name, os.path.join(root, name))21 elif top.endswith('.zip'):22 with zipfile.ZipFile(top, 'r') as zip:23 for name in zip.namelist():24 if name.endswith('.jar'):25 with zip.open(name, 'r') as jar:26 yield from iter_classes(os.path.basename(name), jar)27 elif top.endswith('.jar'):28 yield from iter_classes(os.path.basename(top), top)29 else:30 raise NotImplementedError31def scan_jars(top):32 class2jars = defaultdict(set);33 for jarname, classname in iter_jars(top):34 class2jars[classname].add(jarname)35 return class2jars36a = scan_jars(args.jarsa)37b = scan_jars(args.jarsb)38intersection = set(a.keys()) & set(b.keys())39if not intersection:40 print("no overlap")41for cls in intersection:42 print(f"{cls} is duplicated")...
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!!