How to use keyboardinterrupt method in Nose

Best Python code snippet using nose

collector.py

Source:collector.py Github

copy

Full Screen

1#!/usr/bin/env python32import sys3sys.path.append("/priv-libs/libs")4from web_client import test_auth, test_token, post_enc_data5from priv_common import load_yaml_file, get_all_keys, encrypt_as_de, encrypt_as_cpabe6from priv_common import encrypt_as_timestamp, decrypt_cpabe, match_re_to_keys, _to_bool7import pickle8# import threading9import socket10from concurrent.futures.thread import ThreadPoolExecutor11import signal12import json13from pprint import pprint14import traceback15def create_indexes(enc_record:dict, record_keys:list, record:dict, enc_policy, key, debug=False):16 # pprint(enc_policy)17 index_created = False18 record_keys = set(record_keys) # create new object and dont change original19 # create index for exact matches20 try:21 for m in enc_policy["exact"]:22 try:23 k = m["match"]24 dat = record[k]25 enc_dat = encrypt_as_de(dat, key)26 if debug:27 print("{}: {}".format(k,"DE, index"), flush=True)28 try:29 enc_record["index"].append(enc_dat)30 record_keys.discard(k)31 index_created = index_created or True32 except KeyboardInterrupt:33 raise KeyboardInterrupt34 except :35 enc_record["index"] = list()36 enc_record["index"].append(enc_dat)37 record_keys.discard(k)38 index_created = index_created or True39 except KeyboardInterrupt:40 raise KeyboardInterrupt41 except:42 # traceback.print_exc()43 continue44 except KeyboardInterrupt:45 raise KeyboardInterrupt46 except:47 # traceback.print_exc()48 pass49 # create index for regex matches50 try:51 for m in enc_policy["regex"]:52 try:53 reg_k = m["match"]54 matched_keys = match_re_to_keys(reg_k, list(record_keys))55 for k in matched_keys:56 try:57 dat = record[k]58 enc_dat = encrypt_as_de(dat, key)59 if debug:60 print("{}: {}, index".format(k,"DE"), flush=True)61 try:62 enc_record["index"].append(enc_dat)63 record_keys.discard(k)64 index_created = index_created or True65 except KeyboardInterrupt:66 raise KeyboardInterrupt67 except (NameError,AttributeError,KeyError):68 enc_record["index"] = list()69 enc_record["index"].append(enc_dat)70 record_keys.discard(k)71 index_created = index_created or True72 except KeyboardInterrupt:73 raise KeyboardInterrupt74 except:75 traceback.print_exc()76 continue77 except KeyboardInterrupt:78 raise KeyboardInterrupt79 except:80 # traceback.print_exc()81 continue82 except KeyboardInterrupt:83 raise KeyboardInterrupt84 except:85 # traceback.print_exc()86 pass87 # if we can not create index for any of the matching record return false, sefety measure88 return index_created89def timestamp_match(enc_record:dict, record_keys:list, record:dict, enc_policy, key, enc_params, debug=False):90 # pprint(enc_policy)91 record_keys = set(record_keys) # create new object and dont change original92 # create index for exact matches93 try:94 for m in enc_policy["exact"]:95 try:96 k = m97 dat = record[k]98 enc_dat = encrypt_as_timestamp(dat, key, enc_params)99 if debug:100 print("{}: {}".format(k,"TIMESTAMP"), flush=True)101 if not enc_dat:102 continue103 try:104 enc_record["timestamp"].append(enc_dat)105 record_keys.discard(k)106 except KeyboardInterrupt:107 raise KeyboardInterrupt108 except (NameError,AttributeError,KeyError):109 enc_record["timestamp"] = list()110 enc_record["timestamp"].append(enc_dat)111 record_keys.discard(k)112 except KeyboardInterrupt:113 raise KeyboardInterrupt114 except:115 # traceback.print_exc()116 continue117 except KeyboardInterrupt:118 raise KeyboardInterrupt119 except:120 # traceback.print_exc()121 pass122 # create index for regex matches123 try:124 for m in enc_policy["regex"]:125 try:126 reg_k = m127 matched_keys = match_re_to_keys(reg_k, list(record_keys))128 for k in matched_keys:129 try:130 dat = record[k]131 enc_dat = encrypt_as_timestamp(dat, key, enc_params)132 if debug:133 print("{}: {}".format(k,"TIMESTAMP"), flush=True)134 if not enc_dat:135 continue136 try:137 enc_record["timestamp"].append(enc_dat)138 record_keys.discard(k)139 except KeyboardInterrupt:140 raise KeyboardInterrupt141 except:142 enc_record["timestamp"] = list()143 enc_record["timestamp"].append(enc_dat)144 record_keys.discard(k)145 except KeyboardInterrupt:146 raise KeyboardInterrupt147 except:148 # traceback.print_exc()149 continue150 except KeyboardInterrupt:151 raise KeyboardInterrupt152 except:153 traceback.print_exc()154 continue155 except KeyboardInterrupt:156 raise KeyboardInterrupt157 except:158 # traceback.print_exc()159 pass160def exact_match(enc_record:dict, record_keys:list, record:dict, enc_policy, de_key, cpabe_pk, debug=False):161 new_record_keys = set(record_keys) # create new object and dont change original162 try:163 for m in enc_policy:164 try:165 k = m["match"]166 dat = record[k]167 if "remove" in m:168 if _to_bool(m["remove"]):169 new_record_keys.discard(k)170 continue171 try:172 want_de = _to_bool(m["de_encrypt"])173 except KeyboardInterrupt:174 raise KeyboardInterrupt175 except KeyError:176 want_de = False177 if want_de:178 de_k = "de_"+k179 enc_dat_de = encrypt_as_de(dat, de_key)180 enc_record[de_k] = enc_dat_de181 new_record_keys.discard(k)182 if "abe_pol" in m:183 if debug:184 print("{}: {}".format(k,m["abe_pol"]), flush=True)185 abe_k = "cpabe_"+k186 enc_dat_abe = encrypt_as_cpabe(dat,m["abe_pol"], cpabe_pk)187 enc_record[abe_k] = enc_dat_abe188 new_record_keys.discard(k)189 except KeyboardInterrupt:190 raise KeyboardInterrupt191 except:192 # traceback.print_exc()193 continue194 except KeyboardInterrupt:195 raise KeyboardInterrupt196 except:197 # traceback.print_exc()198 pass199 record_keys.clear()200 record_keys.extend(new_record_keys)201def regex_match(enc_record:dict, record_keys:list, record:dict, enc_policy, de_key, cpabe_pk, debug=False):202 new_record_keys = set(record_keys) # create new object and dont change original203 try:204 for m in enc_policy:205 try:206 reg_k = m["match"]207 matched_keys = match_re_to_keys(reg_k, list(record_keys))208 for k in matched_keys:209 try:210 dat = record[k]211 if "remove" in m:212 if _to_bool(m["remove"]):213 new_record_keys.discard(k)214 continue215 try:216 want_de = _to_bool(m["de_encrypt"])217 except KeyboardInterrupt:218 raise KeyboardInterrupt219 except KeyError:220 want_de = False221 if want_de:222 de_k = "de_"+k223 enc_dat_de = encrypt_as_de(dat, de_key)224 enc_record[de_k] = enc_dat_de225 new_record_keys.discard(k)226 if "abe_pol" in m:227 if debug:228 print("{}: {}".format(k,m["abe_pol"]), flush=True)229 abe_k = "cpabe_"+k230 enc_dat_abe = encrypt_as_cpabe(dat,m["abe_pol"], cpabe_pk)231 enc_record[abe_k] = enc_dat_abe232 new_record_keys.discard(k)233 except KeyboardInterrupt:234 raise KeyboardInterrupt235 except:236 # traceback.print_exc()237 # print()238 continue239 except KeyboardInterrupt:240 raise KeyboardInterrupt241 except:242 # traceback.print_exc()243 continue244 except KeyboardInterrupt:245 raise KeyboardInterrupt246 except:247 # traceback.print_exc()248 pass249 record_keys.clear()250 record_keys.extend(new_record_keys)251def default_match(enc_record:dict, record_keys:list, record:dict, enc_policy, de_key, cpabe_pk, debug=False):252 # if we can not enc using deff policy for any field in record_keys return false, sefety measure253 new_record_keys = set(record_keys) # create new object and dont change original YET254 try:255 256 try:257 want_de = _to_bool(enc_policy["de_encrypt"])258 except KeyboardInterrupt:259 raise KeyboardInterrupt260 except KeyError:261 want_de = False262 for k in record_keys:263 try:264 dat = record[k]265 if want_de:266 de_k = "de_"+k267 enc_dat_de = encrypt_as_de(dat, de_key)268 enc_record[de_k] = enc_dat_de269 new_record_keys.discard(k)270 if "abe_pol" in enc_policy:271 abe_pol = enc_policy["abe_pol"]272 if debug:273 print("{}: {}".format(k,abe_pol), flush=True)274 abe_k = "cpabe_"+k275 enc_dat_abe = encrypt_as_cpabe(dat,abe_pol, cpabe_pk)276 enc_record[abe_k] = enc_dat_abe277 new_record_keys.discard(k)278 except KeyboardInterrupt:279 raise KeyboardInterrupt280 except:281 traceback.print_exc()282 continue283 except KeyboardInterrupt:284 raise KeyboardInterrupt285 except:286 # traceback.print_exc()287 return False288 record_keys.clear()289 record_keys.extend(new_record_keys)290 return True291def post_record(api_url, enc_record:dict, debug=False, auth=None, post=True):292 #post data to server293 if post:294 res = post_enc_data(api_url, enc_record, debug=debug, auth=auth)295 return res296 else:297 return False298def conn_to_record(conn):299 size = 1024300 record_bytes = bytes()301 try:302 while True:303 data = conn.recv(size)304 if data:305 record_bytes += data306 else:307 break308 except:309 traceback.print_exc()310 return None311 try:312 record_str = record_bytes.decode()313 # print(record_str)314 record = json.loads(record_str)315 return record316 except:317 traceback.print_exc()318 return None319def handle_client(conn, addr, max_numb_retries_post, DEBUG,other_args, auth=None, POST_DATA=True, DEBUG_WAS_POST=False):320 print("N",end="",flush=True)321 record = conn_to_record(conn)322 if not record: 323 # print("closing")324 try:325 conn.close()326 except:327 traceback.print_exc()328 pass329 finally:330 return331 print("R",end="",flush=True)332 enc_record = encrypt_record(record, **other_args)333 print("E",end="",flush=True)334 # try:335 # conn.close()336 # except:337 # pass338 # if not enc_record:339 # return340 if not enc_record:341 try:342 conn.close()343 except:344 pass345 finally:346 return347 post_succ = post_record(config_collector["backend_server"]["url"], enc_record, debug=DEBUG, auth=auth, post=POST_DATA)348 if DEBUG_WAS_POST:349 print("posted?", post_succ, flush=True)350 if POST_DATA: # only retry if we are actually posting on failed351 for i in range(max_numb_retries_post):352 if post_succ:353 print("P",end="",flush=True)354 break355 else:356 print("F",end="",flush=True)357 if DEBUG:358 print("retrying to post...", flush=True)359 post_succ = post_record(config_collector["backend_server"]["url"], enc_record, debug=DEBUG, auth=auth, post=POST_DATA)360 if DEBUG_WAS_POST:361 print("posted?", post_succ, flush=True)362 363 if not post_succ:364 print("L",end="",flush=True)365 366 try:367 conn.close()368 except:369 pass370 finally:371 return372def encrypt_record(record, keychain, config_collector, 373 SHOW_ENC_POL, DEBUG, PRINT_LEFT_KEYS, PRINT_ENCRYPTED_RECORD,374 PRINT_INCOMING_RECORD):375 record_keys = list(record.keys()) # will be used up376 enc_record = dict()377 if PRINT_INCOMING_RECORD:378 print()379 print("="*50, flush=True)380 pprint(record)381 print("="*50, flush=True)382 # master_key_set.update(set(record_keys))383 # print("all keys:",record_keys)384 try:385 index_policy = config_collector['policy']['index']386 except:387 sys.exit("Index policy not found. Add ['policy']['index'] to configuration.")388 succ = create_indexes(enc_record, record_keys, record, index_policy , keychain["de"], debug=SHOW_ENC_POL)389 if not succ:390 print("skiping, no index created", flush=True)391 # if ONLY_ONE:392 # break393 return None394 395 if PRINT_LEFT_KEYS:396 print("before time match:",record_keys, flush=True)397 try:398 # print("trying timestamp", flush=True)399 timestamp_policy = config_collector['policy']['timestamp']400 timestamp_match(enc_record, record_keys, record, timestamp_policy , keychain["ore"], keychain["ore_params"], debug=SHOW_ENC_POL)401 # print("tryed timestamp", flush=True)402 except KeyError:403 pass404 if PRINT_LEFT_KEYS:405 print("before exact match:", record_keys, flush=True)406 try:407 exact_policy = config_collector['policy']['exact']408 exact_match(enc_record, record_keys, record, exact_policy, keychain["de"], keychain["pk"], debug=SHOW_ENC_POL)409 except KeyError:410 pass411 412 if PRINT_LEFT_KEYS:413 print("before regex match:", record_keys, flush=True)414 try:415 regex_policy = config_collector['policy']['regex']416 regex_match(enc_record, record_keys, record, regex_policy, keychain["de"], keychain["pk"], debug=SHOW_ENC_POL)417 except KeyError:418 pass419 if PRINT_LEFT_KEYS:420 print("left for default:", record_keys, flush=True)421 try:422 default_policy = config_collector['policy']['default']423 except KeyError:424 print("WARNING: 'ALL or PUBLIC or DEFAULT' is being used as default fallback as no default policy was provided.")425 default_policy = "ALL or PUBLIC or DEFAULT"426 default_match(enc_record, record_keys, record, default_policy, keychain["de"], keychain["pk"], debug=SHOW_ENC_POL)427 if PRINT_LEFT_KEYS:428 print("fields left (should be empty):",record_keys, flush=True)429 if PRINT_ENCRYPTED_RECORD:430 print()431 print('#'*50, flush=True)432 pprint(enc_record)433 print('#'*50, flush=True)434 return enc_record435def signal_handler(sig, frame):436 global EXIT_MAINLOOP, SIGINT_COUNT437 if sig == signal.SIGINT:438 if SIGINT_COUNT >= 1:439 sys.exit("Forced exiting now...")440 print('\nExiting: waiting for threads to finish working...(Press Ctrl+c to force)', flush=True)441 EXIT_MAINLOOP = True442 SIGINT_COUNT += 1443if __name__ == "__main__":444 # parser = create_parser()445 # args = parser.parse_args()446 config_f_name = "/config.yaml"#sys.argv[1] 447 config_collector = load_yaml_file(config_f_name)448 try:449 DEBUG = config_collector["debug"]["enabled"]450 except:451 DEBUG = False452 try:453 ONLY_ONE = config_collector["debug"]["process_only_one"]454 except:455 ONLY_ONE = False456 try:457 SHOW_ENC_POL = config_collector["debug"]["show_enc_policy"]458 except:459 SHOW_ENC_POL = False460 try:461 SHOW_POL_CONFIG = config_collector["debug"]["print_policy_config"]462 except:463 SHOW_POL_CONFIG = False464 465 try:466 POST_DATA = not config_collector["debug"]["do_not_post_data"]467 except:468 POST_DATA = True469 try:470 PRINT_LEFT_KEYS = config_collector["debug"]["print_left_keys"]471 except:472 PRINT_LEFT_KEYS = False473 try:474 PRINT_ENCRYPTED_RECORD = config_collector["debug"]["print_encrypted_record"]475 except:476 PRINT_ENCRYPTED_RECORD = False477 try:478 PRINT_INCOMING_RECORD = config_collector["debug"]["print_incoming_record"]479 except:480 PRINT_INCOMING_RECORD = False481 482 try:483 DEBUG_WAS_POST = config_collector["debug"]["print_was_posted"]484 except:485 DEBUG_WAS_POST = False486 try:487 max_numb_retries_post = config_collector["backend_server"]["max_post_retries"]488 if max_numb_retries_post < 0:489 max_numb_retries_post = 0490 except:491 max_numb_retries_post = 0492 try:493 enc_worker_threads = config_collector["enc_worker_threads"]494 if enc_worker_threads <= 0:495 enc_worker_threads = 10496 except:497 enc_worker_threads = 10498 try:499 web_conn_listen = config_collector["web_conn_listen"]500 if web_conn_listen < 0:501 web_conn_listen = 0502 except:503 web_conn_listen = 0504 basic_auth = None505 try:506 basic_auth_user = config_collector["basic_auth"]["user"]507 try:508 basic_auth_pass = config_collector["basic_auth"]["pass"]509 basic_auth = (basic_auth_user, basic_auth_pass)510 print("Basic auth: enabled")511 except:512 exit("Basic auth: no password specified. Exiting.\n")513 except:514 print("Basic auth: disabled")515 basic_auth = None516 if basic_auth != None:517 if not test_auth(config_collector["kms"]["url"], basic_auth):518 exit("Test failed: KMS basic auth. quiting.")519 if not test_auth(config_collector["backend_server"]["url"], basic_auth):520 exit("Test failed: backend basic auth. quiting.")521 if not test_token(config_collector["kms"]["url"],config_collector["kms_access_key"], basic_auth):522 exit("Test failed: bad kms_access_key, KMS server could also be down.")523 key_arguments = {524 "kms_url": config_collector["kms"]["url"],525 "kms_access_key": config_collector["kms_access_key"],526 "DE_key_location": config_collector["key_files"]["de"],527 "ORE_key_location": config_collector["key_files"]["ore"],528 "ORE_params_location": config_collector["key_files"]["ore_params"],529 "cpabe_pk_location": config_collector["key_files"]["cpabe_pub"],530 # uncomment sk line to get that key, not needed here 531 # "cpabe_sk_location": config_collector["key_files"]["cpabe_secret"],532 "auth": basic_auth533 }534 keychain = get_all_keys(**key_arguments)535 if SHOW_POL_CONFIG:536 print("#"*21 +" config " + "#"*21, flush=True)537 pprint(config_collector)538 print("#"*50, flush=True)539 # master_key_set = set()540 # for record in honeypot_testdata:541 enc_argument = {542 "keychain": keychain,543 "config_collector": config_collector,544 "SHOW_ENC_POL": SHOW_ENC_POL,545 "DEBUG": DEBUG ,546 "PRINT_LEFT_KEYS": PRINT_LEFT_KEYS,547 "PRINT_ENCRYPTED_RECORD": PRINT_ENCRYPTED_RECORD,548 "PRINT_INCOMING_RECORD": PRINT_INCOMING_RECORD549 # "max_numb_retries_post": max_numb_retries_post550 }551 serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)552 serversocket.settimeout(0.2)553 serversocket.bind(("0.0.0.0", 8080))554 serversocket.listen(web_conn_listen)555 EXIT_MAINLOOP = False556 SIGINT_COUNT = 0557 signal.signal(signal.SIGINT, signal_handler)558 print("Ready, waiting for new connetions...",flush=True)559 with ThreadPoolExecutor(max_workers=enc_worker_threads) as executor:560 while not EXIT_MAINLOOP:561 try:562 conn, addr = serversocket.accept()563 except socket.timeout:564 continue # allow to exit loop if needed565 # threading.Thread(target = handle_client,args = (conn,addr)).start()566 executor.submit(handle_client, conn, addr,max_numb_retries_post,DEBUG, enc_argument, auth=basic_auth, POST_DATA=POST_DATA, DEBUG_WAS_POST=DEBUG_WAS_POST)567 568 if ONLY_ONE:569 break570 # exiting with will have same effects as excutor shutdown571 # will raise execption if new jobs submitted572 # will wait for all queue jobs to finish, dealocate resources573 # executor.shutdown(wait=True, cancel_futures=False)574 # will get here after all threads finish575 print("",flush=True)576# todo 577# remove de as part of policy "de_encrypt"?578# add a argument parser?579# def create_parser():580# parser = argparse.ArgumentParser(description='Collector encryption module.')581# parser.add_argument('--user', metavar='USER', type=str, dest='auth_user',582# default=None,583# help='Basic auth for server, user. must be used with --pass (default: off)')584# parser.add_argument('--pass', metavar='id', type=str, dest='auth_pass',585# default=None,586# help='Basic auth for server, pass')...

Full Screen

Full Screen

Method.py

Source:Method.py Github

copy

Full Screen

1from src.AbstractClass.ElePack import *2from src.Module.JumperWire import *3from src.Model.SingleLineModel import *4import numpy as np5#################################################################################6# 显示元素7def show_ele(vessel, para=''):8 if isinstance(vessel, (list, set)):9 list_t = list()10 for ele in vessel:11 if para == '':12 list_t.append(ele.__repr__())13 else:14 list_t.append(ele.__dict__[para].__repr__())15 list_t.sort()16 for ele in list_t:17 print(ele)18 elif isinstance(vessel, (dict, ElePack)):19 keys = sorted(list(vessel.keys()))20 for key in keys:21 if para == '':22 print(key, ':', vessel[key])23 else:24 print(vessel[key].__dict__[para])25#################################################################################26# 获取频率27def generate_frqs(freq1, m_num, flip_flag=False):28 frqs = list()29 if flip_flag:30 freq1.change_freq()31 for _ in range(m_num):32 frqs.append(freq1)33 freq1 = freq1.copy()34 freq1.change_freq()35 return frqs36#################################################################################37# 获取电容数38def get_c_nums(m_frqs, m_lens):39 c_nums = list()40 for num in range(len(m_frqs)):41 freq = m_frqs[num]42 length = m_lens[num]43 c_num = get_c_num(freq, length)44 c_nums.append(c_num)45 return c_nums46#################################################################################47# 获取电容数48def get_c_num(freq, length):49 if 0 < length < 300:50 index = 051 elif length == 300:52 index = 153 elif length > 300:54 index = int((length - 251) / 50)55 else:56 index = 057 CcmpTable1 = [0, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 15, 16, 17, 18, 19, 20, 20, 21, 22, 23, 24, 25]58 CcmpTable2 = [0, 4, 5, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 18]59 freq = freq.value60 if freq == 1700 or freq == 2000:61 table = CcmpTable162 elif freq == 2300 or freq == 2600:63 table = CcmpTable264 else:65 table = []66 c_num = table[index]67 return c_num68#################################################################################69# 获取钢轨电流70def get_i_trk(line, posi, direct='右'):71 i_trk = None72 if direct == '右':73 if line.node_dict[posi].r_track is not None:74 i_trk = line.node_dict[posi].r_track['I1'].value_c75 else:76 i_trk = 0.077 elif direct == '左':78 if line.node_dict[posi].l_track is not None:79 i_trk = line.node_dict[posi].l_track['I2'].value_c80 else:81 i_trk = 0.082 return i_trk83#################################################################################84# 获取耦合系数85def get_mutual(distance):86 l1 = 687 d = 1.43588 k1 = 1389 k_mutual = k1 / np.log((l1 * l1 - d * d) / l1 / l1)90 l2 = distance91 k2 = k_mutual * np.log((l2 * l2 - d * d) / l2 / l2)92 return k293#################################################################################94# 配置SVA'互感95def config_sva1_mutual(model, temp, zm_sva):96 # zm_sva = 2 * np.pi * 1700 * 1 * 1e-6 * 1j97 m1 = model98 # temp_list = [(3, 4, '右'), (3, 4, '左') ,(4, 3, '左') ,(4, 3, '左')]99 # for temp in temp_list:100 line_zhu = '线路' + str(temp[0])101 line_bei = '线路' + str(temp[1])102 str_t = '线路组_' + line_bei + '_地面_区段1_' + temp[2] + '调谐单元_6SVA1_方程1'103 equ_t = m1.equs.equ_dict[str_t]104 str_t = '线路组_' + line_zhu + '_地面_区段1_' + temp[2] + '调谐单元'105 varb1 = m1[line_zhu]['元件'][str_t]['6SVA1']['I1']106 varb2 = m1[line_zhu]['元件'][str_t]['6SVA1']['I2']107 equ_t.varb_list.append(varb1)108 equ_t.varb_list.append(varb2)109 equ_t.coeff_list = np.append(equ_t.coeff_list, zm_sva)110 equ_t.coeff_list = np.append(equ_t.coeff_list, -zm_sva)111#################################################################################112# 配置跳线组113def config_jumpergroup(*jumpers):114 for jumper in jumpers:115 if not isinstance(jumper, JumperWire):116 raise KeyboardInterrupt('类型错误:参数需要为跳线类型')117 else:118 jumper.jumpergroup = list(jumpers)119#################################################################################120# 合并节点121def combine_node(nodes):122 if len(nodes) < 1:123 raise KeyboardInterrupt('数量错误:合并node至少需要1个参数')124 posi = nodes[0].posi125 node_new = Node(posi)126 node_new.node_type = 'combined'127 node_new.l_track = list()128 node_new.r_track = list()129 for node in nodes:130 if not isinstance(node, Node):131 raise KeyboardInterrupt('类型错误:合并node参数需要为节点类型')132 elif not node.posi == posi:133 raise KeyboardInterrupt('位置错误:合并node需要节点在相同水平位置')134 else:135 if node.l_track is not None:136 node_new.l_track.append(node.l_track)137 if node.r_track is not None:138 node_new.r_track.append(node.r_track)139 for key, value in node.element.items():140 node_new.element[key] = value141 node_new.equs.add_equations(node.equs)142 node_new.group_type = 'combined'143 return node_new144#################################################################################145# 合并节点组146def combine_node_group(lines):147 groups = NodeGroup()148 posi_set = set()149 for line in lines:150 posi_set.update(line.node_dict.posi_set)151 posi_list = list(posi_set)152 posi_list.sort()153 for posi in posi_list:154 nodes_list = list()155 for line in lines:156 if posi in line.node_dict.keys():157 nodes_list.append(line.node_dict[posi])158 nodes = tuple(nodes_list)159 node_new = combine_node(nodes)160 groups.node_dict[posi] = node_new161 return groups162#################################################################################163# 检查输入164def check_input(df):165 para = dict()166 para['FREQ'] = [1700, 2000, 2300, 2600]167 para['SEND_LEVEL'] = [1, 2, 3, 4, 5, 6, 7, 8, 9]168 para['CABLE_LENGTH'] = [7.5, 10]169 para['C_NUM'] = [0, 1, 2, 3, 4, 5, 6, 7]170 para['TB_MODE'] = ['双端TB', '左端单TB', '右端单TB', '无TB']171 num_len = len(list(df['序号']))172 for temp_temp in range(num_len):173 df_input = df.iloc[temp_temp]174 # 检查主串名称格式175 name = str(df_input['主串区段'])176 if len(name) <= 8:177 pass178 else:179 raise KeyboardInterrupt("主串区段应填写长度小于等于8位的字符串")180 # 检查被串名称格式181 name = str(df_input['被串区段'])182 if len(name) <= 8:183 pass184 else:185 raise KeyboardInterrupt("被串区段应填写长度小于等于8位的字符串")186 # 检查主串方向格式187 if df_input['主串方向'] == '左发' or df_input['主串方向'] == '右发':188 pass189 else:190 raise KeyboardInterrupt("主串方向应填写'左发'或'右发'")191 # 检查被串方向格式192 if df_input['被串方向'] == '左发' or df_input['被串方向'] == '右发':193 pass194 else:195 raise KeyboardInterrupt("被串方向应填写'左发'或'右发'")196 # 检查主串区段长度格式197 if 0 <= df_input['主串区段长度(m)'] <= 650:198 pass199 else:200 raise KeyboardInterrupt("'主串区段长度(m)'应填写0~650的实数")201 # 检查被串区段长度格式202 if 0 <= df_input['被串区段长度(m)'] <= 650:203 pass204 else:205 raise KeyboardInterrupt("'被串区段长度(m)'应填写0~650的实数")206 # 检查被串相对位置格式207 if -650 <= df_input['被串相对位置(m)'] <= 650:208 pass209 else:210 raise KeyboardInterrupt("'被串相对位置(m)'应填写-650~650的实数")211 # 检查耦合系数格式212 if 0 < df_input['耦合系数'] <= 40:213 pass214 else:215 raise KeyboardInterrupt("'耦合系数'应填写大于0小于等于40的实数")216 # 检查主串电平级格式217 if df_input['主串电平级'] in para['SEND_LEVEL']:218 pass219 else:220 raise KeyboardInterrupt("'主串电平级'应填写1~9的整数")221 # 检查主串频率格式222 if df_input['主串频率(Hz)'] in para['FREQ']:223 pass224 else:225 raise KeyboardInterrupt("'主串频率(Hz)'应填写四种标准载频之一")226 # 检查被串频率格式227 if df_input['被串频率(Hz)'] in para['FREQ']:228 pass229 else:230 raise KeyboardInterrupt("'被串频率(Hz)'应填写四种标准载频之一")231 # 检查主串电缆长度格式232 if df_input['主串电缆长度(km)'] in para['CABLE_LENGTH']:233 pass234 else:235 raise KeyboardInterrupt("'主串电缆长度(km)'应填写7.5或10")236 # 检查被串电缆长度格式237 if df_input['被串电缆长度(km)'] in para['CABLE_LENGTH']:238 pass239 else:240 raise KeyboardInterrupt("'被串电缆长度(km)'应填写7.5或10")241 # 检查主串电容数格式242 if df_input['主串电容数(含TB)'] in para['C_NUM']:243 pass244 else:245 raise KeyboardInterrupt("'主串电容数(含TB)'应填写0~7之间的整数")246 # 检查被串电容数格式247 if df_input['被串电容数(含TB)'] in para['C_NUM']:248 pass249 else:250 raise KeyboardInterrupt("'被串电容数(含TB)'应填写0~7之间的整数")251 # 检查主串电容值格式252 if 25 <= df_input['主串电容值(μF)'] <= 80:253 pass254 else:255 raise KeyboardInterrupt("'主串电容值(μF)'应填写25~80的实数")256 # 检查被串电容值格式257 if 25 <= df_input['被串电容值(μF)'] <= 80:258 pass259 else:260 raise KeyboardInterrupt("'被串电容值(μF)'应填写25~80的实数")261 # 检查主串道床电阻格式262 if 0 < df_input['主串道床电阻(Ω·km)'] <= 10000:263 pass264 else:265 raise KeyboardInterrupt("'主串道床电阻(Ω·km)'应填写0~10000的正实数")266 # 检查被串道床电阻格式267 if 0 < df_input['被串道床电阻(Ω·km)'] <= 10000:268 pass269 else:270 raise KeyboardInterrupt("'被串道床电阻(Ω·km)'应填写0~10000的正实数")271 # 检查TB模式格式272 if df_input['TB模式'] in para['TB_MODE']:273 pass274 else:275 raise KeyboardInterrupt("'TB模式'应填写标准格式")276def get_section_length():277 import itertools278 param = list()279 zhu_list = range(50, 601, 50)280 for offset in range(50, 301, 50):281 for len1 in zhu_list:282 l_list = [-offset, offset]283 r_list = [len1 - offset, len1 + offset]284 for l_pos, r_pos in itertools.product(l_list, r_list):285 tmp = Param20201307(286 len_zhu=len1,287 l_pos=l_pos,288 r_pos=r_pos,289 )290 if tmp.flg is True:291 param.append(tmp)292 print(tmp.lens_zhu, tmp.lens_bei, tmp.offset, tmp.index_bei)293 return param294class LengthParam:295 def __init__(self):296 self.zhu_length = list()297 self.bei_length = list()298 self.offset = 0299class Param20201307:300 def __init__(self, len_zhu, l_pos, r_pos):301 offset = abs(l_pos)302 self.flg = True303 self.l_pos = l_pos304 self.r_pos = r_pos305 self.lens_zhu = [len_zhu]306 tmp = r_pos - l_pos307 self.lens_bei = [len_zhu, tmp, len_zhu]308 # print(self.lens_bei)309 self.offset = None310 self.index_bei = None311 if abs(r_pos) < offset:312 self.flg = False313 if abs(len_zhu - l_pos) < offset:314 self.flg = False315 if r_pos <= l_pos:316 self.flg = False317 if r_pos - l_pos > 600:318 self.flg = False319 if l_pos < 0:320 self.offset = l_pos321 self.lens_bei.pop(0)322 self.index_bei = 0323 if r_pos >= len_zhu:324 self.lens_bei.pop(-1)325 elif l_pos > 0:326 self.offset = l_pos - len_zhu327 self.index_bei = 1328 if r_pos >= len_zhu:329 self.lens_bei.pop(-1)330def parallel(z1, z2):331 return (z1 * z2) / (z1 + z2)332def cal_zl(zpt, zin):333 zj = (0.037931222832602786+0.3334597710765984j)334 zca = (0.006459333+0.030996667j)335 z1 = (zpt * zin) / (zpt + zin) + zca336 return (z1 * zj) / (z1 + zj)337if __name__ == '__main__':338 # m_lens = [700, 700, 700]339 # m_frqs = generate_frqs(Freq(2600), 3)340 # c_nums = get_c_nums(m_frqs, m_lens)...

Full Screen

Full Screen

tdw.py

Source:tdw.py Github

copy

Full Screen

1#!/usr/bin/env python2""" Copyright (c) 2010 Ma Can <ml.macana@gmail.com>3This is the core TDW runtime library, enjoy it :)4"""5import sys, re, time6from hive_service import ThriftHive7from hive_service.ttypes import HiveServerException8from thrift import Thrift9from thrift.transport import TSocket10from thrift.transport import TTransport11from thrift.protocol import TBinaryProtocol12from array import *13def to_type(line, t):14 '''Type conversion'''15 if t == 'int':16 return int(line)17 elif t == 'bigint':18 return long(line)19 elif t == 'array<int>':20 line = line.strip(" ")21 line = line.strip("[")22 line = line.rstrip(" ")23 line = line.rstrip("]")24 l = line.split(",")25 for i in range(0, len(l)):26 if l[i] == "":27 return array('i')28 else:29 l[i] = int(l[i])30 return array('i', l)31 elif t == 'string':32 return str(line)33class dynamic_type:34 '''Dynamic Type Support'''35 pass36class TDW:37 '''This is the runtime TDW class.'''38 running = True39 40 def __init__(self, client=None):41 '''do init job'''42 self.cli = client43 44 def do_exit(self):45 '''begin to exit'''46 self.running = False47 def execute(self, query):48 '''Execute a SQL query and return the result LIST[0:]'''49 res = None50 try:51 if self.running:52 res = self.cli.execute(query)53 else:54 raise IOError (-2, "Interrupted by the caller or fored exit.")55 except KeyboardInterrupt:56 print ("Recv KeyboardInterrupt, please wait for this SQL "57 "execution (hint: %s)" % res)58 try: 59 if res == None: self.cli.recv_execute()60 except KeyboardInterrupt:61 self.do_exit()62 raise IOError (4, "Interrupted by the caller or fored exit.")63 except Exception, e:64 print "Exception: %s" % str(e)65 self.do_exit()66 raise IOError (4, "Interrupted by the caller or fored exit.")67 self.do_exit()68 try:69 res = self.cli.fetchAll()70 return res71 except KeyboardInterrupt:72 print "Recv KeyboardInterrupt, your client should be reset."73 self.do_exit()74 raise IOError (4, "Interrupted by the caller or fored exit.")75 def execute2int(self, query):76 '''Execute a SQL query and return a INT result'''77 try:78 if self.running:79 res = self.cli.execute(query)80 else:81 raise IOError (-2, "Interrupted by the caller or fored exit.")82 except KeyboardInterrupt:83 print "Recv KeyboardInterrupt, please wait for this SQL execution"84 try: 85 if res == None: self.cli.recv_execute()86 except KeyboardInterrupt:87 self.do_exit()88 raise IOError (4, "Interrupted by the caller or fored exit.")89 except Exception, e:90 print "Exception: %s" % str(e)91 self.do_exit()92 raise IOError (4, "Interrupted by the caller or fored exit.")93 self.do_exit()94 try:95 res = self.cli.fetchAll()96 return int(res[0])97 except TypeError, e :98 print "Result '%s' to INT failed %s" % (res[0], e.message)99 raise IOError (-3, "Result type transform to INT failed, "100 "TypeError.")101 except ValueError :102 print "Result '%s' to INT failed, ValueError" % res[0]103 raise IOError (-3, "Result type transform to INT failed, "104 "ValueError.")105 except KeyboardInterrupt:106 print "Recv KeyboardInterrupt, your client should be reset."107 self.do_exit()108 raise IOError (4, "Interrupted by the caller or fored exit.")109 def execute2str(self, query):110 '''Execute a SQL query and return a STRING (LIST[0])'''111 try:112 if self.running:113 res = self.cli.execute(query)114 else:115 raise IOError (-2, "Interrupted by the caller or fored exit.")116 except KeyboardInterrupt:117 print "Recv KeyboardInterrupt, please wait for this SQL execution"118 try: 119 if res == None: self.cli.recv_execute()120 except KeyboardInterrupt:121 self.do_exit()122 raise IOError (4, "Interrupted by the caller or fored exit.")123 except Exception, e:124 print "Exception: %s" % str(e)125 self.do_exit()126 raise IOError (4, "Interrupted by the caller or fored exit.")127 self.do_exit()128 try:129 res = self.cli.fetchAll()130 return str(res[0])131 except TypeError, e:132 print "Result '%s' to STRING failed %s" % (res[0], e.message)133 raise IOError (-3, "Result type transform to STRING failed, "134 "TypeError.")135 except ValueError :136 print "Result '%s' to STRING failed" % res[0]137 raise IOError (-3, "Result type transform to STRING failed, "138 "ValueError.")139 except KeyboardInterrupt:140 print "Recv KeyboardInterrupt, your client should be reset."141 self.do_exit()142 raise IOError (4, "Interrupted by the caller or fored exit.")143 def printf(self, string, res):144 '''Print the result in a formated manner'''145 try:146 if (type(res) == type(str())):147 print string + " " + res148 elif (type(res) == type(list())):149 print "Q: '" + string + "' |=> '" + " ".join(res) + "'"150 elif (type(res) == type(int())):151 print string + " " + str(res)152 elif (type(res) == type(None)):153 print "Argument is Not A Type."154 except ValueError :155 print "printf convert STRING failed"156 raise IOError (-3, "printf convert STRING failed, ValueError.")157 def result_str(self, res):158 '''Convert a SQL result to a STRING'''159 try:160 __res = str(res)161 except:162 return None163 return __res164 def result_list(self, res):165 '''Convert a SQL result to a LIST'''166 try:167 __res = list(res)168 except:169 return None170 return __res171 def result_int(self, res):172 '''Convert a SQL result to a INT'''173 try:174 __res = int(res)175 except:176 return None177 return __res178 def uploadJob(self, fname):179 '''Upload a job file to server'''180 if not self.running:181 raise IOError (-2, "Interrupted by the caller or fored exit.")182 print "Tring to upload Job '%s' ..." % (fname)183 read_data = ""184 try:185 f = open(fname, "r")186 read_data = f.read()187 f.close()188 except IOError, ie:189 print "IOError %s" % ie190 return191 if read_data == "":192 print "[WARN] Read file '" + fname + "' w/ ZERO content."193 # ok to upload the file to hiveserver194 self.cli.uploadJob(read_data)195 def getschema(self):196 '''Get the Hive Schema from the server'''197 try:198 if self.running:199 return str(self.cli.getSchema())200 else:201 raise IOError (-2, "Interrupted by the caller or fored exit.")202 except KeyboardInterrupt:203 print "Recv KeyboardInterrupt, please wait for get schema"204 self.do_exit()205 self.cli.recv_getSchema()206 def getschemax(self):207 '''Get the SQL schema info the the Hive Scheme'''208 try:209 if self.running:210 schema_string = str(self.cli.getSchema())211 else:212 raise IOError (-2, "Interrupted by the caller or fored exit.")213 except KeyboardInterrupt:214 print "Recv KeyboardInterrupt, please wait for get schema"215 self.do_exit()216 self.cli.recv_getSchema()217 return218 # Parse the schema_string219 m = re.findall("name='[^']*", schema_string)220 for i in range(0, len(m)):221 m[i] = m[i].replace("name='", "")222 return m223 def gettypex(self):224 '''Get the SQL type info from the Hive Schema'''225 try:226 if self.running:227 schema_string = str(self.cli.getSchema())228 else:229 raise IOError (-2, "Interrupted by the caller or fored exit.")230 except KeyboardInterrupt:231 print "Recv KeyboardInterrupt, please wait for get schema"232 self.do_exit()233 self.cli.recv_getSchema()234 return235 # Parse the schema_string236 m = re.findall("type='[^']*", schema_string)237 for i in range(0, len(m)):238 m[i] = m[i].replace("type='", "")239 return m240 def parseschema(self, dict, sql_result):241 '''Parse the SQL result list to a list of lists based on the 'type'242 and 'schema' info in DICT'''243 if sql_result == "" or sql_result == None:244 return list()245 if type(sql_result) != type(list()):246 return list()247 result_list = list()248 column_list = dict['schema']249 type_list = dict['type']250 for i in range(0, len(sql_result)):251 if sql_result[i] == "":252 continue253 new_object = dynamic_type()254 sql_line = sql_result[i].split("\t")255 for j in range(0, len(column_list)):256 setattr(new_object, column_list[j], to_type(sql_line[j], 257 type_list[j]))258 result_list.append(new_object)259 return result_list260 261 def tdw_getrowcount(self):262 '''Get the rowcount from server. The same as %rowcount'''263 try:264 if self.running:265 rc = self.cli.getRowCount()266 else:267 raise IOError (-2, "Interrupted by the caller or fored exit.")268 except TypeError, e:269 print "TypeError %s" % e270 raise IOError (-2, "%s" % e)271 except KeyboardInterrupt, e:272 print "Recv KeyboardInterrupt, your client should be reset."273 self.do_exit()274 raise IOError (-2, "%s" % e)275 return long(rc)276 def tdw_raise(self, errno=None, strerror=None):277 '''Raise a TDW/PL exception (IOError actually)'''278 if type(errno) != type(int()):279 errno = -1280 if type(strerror) != type(str()):281 strerror = "TDW/PL default exception."...

Full Screen

Full Screen

envelop_sendRecv.py

Source:envelop_sendRecv.py Github

copy

Full Screen

1#!/usr/bin/env python32# -*- coding: utf-8 -*-3# Andre Augusto Giannotti Scota (https://sites.google.com/view/a2gs/)4import socket5import struct6class connection:7 servsock = 08 clientsock = 0 # TODO: a list/vector to accept multi clients9 def __init__(self):10 self.servsock = 011 self.clientsock = 012 def serverLoad(self, family, socktype)->[bool, str]:13 try:14 self.servsock = socket.socket(family, socktype)15 except OSError as e:16 return([False, f"{e.errno} {e.strerror}"])17 except ConnectionError as e:18 return([False, f"ConnectionError {e}"])19 except KeyboardInterrupt:20 return([False, "KeyboardInterrupt"])21 except Exception as e:22 return([False, e])23 except BaseException as e:24 return([False, f"BaseException {str(e)}"])25 except:26 return([False, "Unknow exception"])27 return([True, "Ok"])28 def serverBindListen(self, port : int, listen : int)->[bool, str]:29 try:30 self.servsock.bind((socket.gethostname(), port))31 self.servsock.listen(listen)32 except OSError as e:33 return([False, f"{e.errno} {e.strerror}"])34 except ConnectionError as e:35 return([False, f"ConnectionError {e}"])36 except KeyboardInterrupt:37 return([False, "KeyboardInterrupt"])38 except Exception as e:39 return([False, e])40 except BaseException as e:41 return([False, f"BaseException {str(e)}"])42 except:43 return([False, "Unknow exception"])44 return([True, "Ok"])45 def sockOpts(self, opt)->[bool, str]:46 try:47 self.servsock.setsockopt(socket.SOL_SOCKET, opt, 1)48 except OSError as e:49 return([False, f"{e.errno} {e.strerror}"])50 except ConnectionError as e:51 return([False, f"ConnectionError {e}"])52 except KeyboardInterrupt:53 return([False, "KeyboardInterrupt"])54 except Exception as e:55 return([False, e])56 except BaseException as e:57 return([False, f"BaseException {str(e)}"])58 except:59 return([False, "Unknow exception"])60 return([True, "Ok"])61 def endServer(self)->[bool, str]:62 try:63 self.servsock.shutdown(socket.SHUT_RDWR)64 except OSError as e:65 return([False, f"{e.errno} {e.strerror}"])66 except ConnectionError as e:67 return([False, f"ConnectionError {e}"])68 except KeyboardInterrupt:69 return([False, "KeyboardInterrupt"])70 except Exception as e:71 return([False, e])72 except BaseException as e:73 return([False, f"BaseException {str(e)}"])74 except:75 return([False, "Unknow exception"])76 return([True, "Ok"])77 def endClient(self)->[bool, str]:78 try:79 self.clientsock.shutdown(socket.SHUT_RDWR)80 except OSError as e:81 return([False, f"{e.errno} {e.strerror}"])82 except ConnectionError as e:83 return([False, f"ConnectionError {e}"])84 except KeyboardInterrupt:85 return([False, "KeyboardInterrupt"])86 except Exception as e:87 return([False, e])88 except BaseException as e:89 return([False, f"BaseException {str(e)}"])90 except:91 return([False, "Unknow exception"])92 return([True, "Ok"])93 def serverAccept(self)->[bool, str, str]:94 try:95 self.clientsock, address = self.servsock.accept()96 except OSError as e:97 return([False, f"{e.errno} {e.strerror}", ""])98 except ConnectionError as e:99 return([False, f"ConnectionError {e}", ""])100 except KeyboardInterrupt:101 return([False, "KeyboardInterrupt", ""])102 except Exception as e:103 return([False, e, ""])104 except BaseException as e:105 return([False, f"BaseException {str(e)}", ""])106 except:107 return([False, "Unknow exception", ""])108 return([True, "Ok", address])109 def connectToServer(self, address, port, family, socktype)->[bool, str]:110 try:111 self.clientsock = socket.socket(family, socktype)112 except OSError as e:113 return([False, f"Erro socket: {e.errno} {e.strerror}"])114 except ConnectionError as e:115 return([False, f"Erro socket: ConnectionError {e}"])116 except KeyboardInterrupt:117 return([False, "Erro socket: KeyboardInterrupt"])118 except Exception as e:119 return([False, e])120 except BaseException as e:121 return([False, f"Erro socket: BaseException {str(e)}"])122 except:123 return([False, "Erro socket: unknow exception"])124 # i hate 'exception' (in c++ too, the ideia). i intentionally do bad code on purpose with it.125 try:126 self.clientsock.connect((address, port))127 except OSError as e:128 return([False, f"Erro connect: {e.errno} {e.strerror}"])129 except ConnectionError as e:130 return([False, f"Erro connect: ConnectionError {e}"])131 except KeyboardInterrupt:132 return([False, "Erro connect: KeyboardInterrupt"])133 except Exception as e:134 return([False, e])135 except BaseException as e:136 return([False, f"Erro connect: BaseException {str(e)}"])137 except:138 return([False, "Erro connect: unknow exception"])139 return([True, "Ok"])140 def sendMsg(self, msg, szToSend)->[bool, str]:141 msgSz = struct.pack('!I', szToSend)142 try:143 self.clientsock.sendall(msgSz)144 self.clientsock.sendall(bytes(msg, "utf-8"))145 except OSError as e:146 return([False, f"{e.errno} {e.strerror}"])147 except ConnectionError as e:148 return([False, f"ConnectionError {e}"])149 except KeyboardInterrupt:150 return([False, "KeyboardInterrupt"])151 except Exception as e:152 return([False, e])153 except BaseException as e:154 return([False, f"BaseException {str(e)}"])155 except:156 return([False, "Unknow exception"])157 return([True, "Ok"])158 def recvMsg(self)->[bool, str, str]:159 HEADERSIZE = 4 # struct.pack('!I', szToSend)160 msgSz = 0161 recvBuf = b''162 chunk = b''163 # reading msg size164 recvBufSz = 0165 while recvBufSz < HEADERSIZE:166 try:167 chunk = self.clientsock.recv(HEADERSIZE - recvBufSz)168 except OSError as e:169 return([False, f"Erro reading msg envelop: {e.errno} {e.strerror}", ""])170 except ConnectionError as e:171 return([False, f"Erro reading msg envelop: ConnectionError {e}", ""])172 except KeyboardInterrupt:173 return([False, "Erro reading msg envelop: KeyboardInterrupt", ""])174 except Exception as e:175 return([False, f"Erro reading msg envelop: {e}", ""])176 except BaseException as e:177 return([False, f"Erro reading msg envelop: BaseException {str(e)}", ""])178 except:179 return([False, "Erro reading msg envelop: Unknow exception", ""])180 if chunk == b'':181 return([False, "Socket connection broken", ""])182 recvBuf = recvBuf + chunk183 recvBufSz = len(recvBuf)184 msgSz = struct.unpack('!I', recvBuf)[0]185 # reading the msg186 recvBuf = b''187 recvBufSz = 0188 while recvBufSz < msgSz:189 try:190 chunk = self.clientsock.recv(msgSz - recvBufSz)191 except OSError as e:192 return([False, f"Erro reading msg: {e.errno} {e.strerror}", ""])193 except ConnectionError as e:194 return([False, f"Erro reading msg: ConnectionError {e}", ""])195 except KeyboardInterrupt:196 return([False, "Erro reading msg: KeyboardInterrupt", ""])197 except Exception as e:198 return([False, f"Erro reading msg: {e}", ""])199 except BaseException as e:200 return([False, f"Erro reading msg: BaseException {str(e)}", ""])201 except:202 return([False, "Erro reading msg: Unknow exception", ""])203 if chunk == b'':204 return([False, "Socket connection broken", ""])205 recvBuf = recvBuf + chunk206 recvBufSz = len(recvBuf)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nose automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful