def beautifyJson(filename): f = open(filename, "r") try: asset = json.loads(f.read()) except Exception as e: print('[!] Error during json parsing') print(filename, e) exit(1) headers = ['name', 'ip', 'os', 'mac', 'manufacturer'] name = asset['fqdn'] if name == "" and "name0" in asset["additional names"]: name = asset["additional names"]["name0"] data = [[ name, asset['ipv4']['address'], asset['os']['cpe'], asset['mac']['address'], asset['mac']['manuf'] ]] table = columnar(data, headers) print(table) headers = ['port', 'service'] data = [] for app in asset['applicative']: service = asset['applicative'][app]['name'] if service == "": service = asset['applicative'][app]['protocol'] data.append([ asset['applicative'][app]['port']['type'] + ' ' + asset['applicative'][app]['port']['number'], service ]) table = columnar(data, headers) print(table) print('\n')
def outstanding_product(): ref = Products.ref product_code = list(ref.get().keys()) product_details = list() table_name = [["Products"]] product_header = [ # ตั้งให้ auto gen "Code", "Catagory", "Name", "Brand", "Unit Price", "Quantity", ] for code in product_code: dict = ref.child(code).get() # dict = ref.order_by_child('%s/Category' % code).get() product_details.append([ code, dict["Category"], dict["Name"], dict["Brand"], dict["UnitPrice"], dict["Quantity"], ]) product_details.sort(key=len) # ทำsort by catagory/code print(columnar(table_name)) print( columnar(product_details, product_header, terminal_width=100, justify="c"))
def main(): """ Entry point of the script """ signal.signal(signal.SIGINT, lambda sig, frame: sys.exit(0)) ret = checkargs(sys.argv) if ret != 0: sys.exit(ret) iio_list = sys.argv[1:] for accel_name in iio_list: vec = get_coordinates(accel_name) vec_str = [list(map(lambda rot: str(rot), vec))] axis_rots = [yaw(vec), pitch(vec), roll(vec)] axis_rots = list( map(lambda rot: round(rot * 180 / math.pi, 2), axis_rots)) axis_rots_strs = [list(map(lambda rot: str(rot) + "°", axis_rots))] print("| ", accel_name.upper()) headers = ["Ax", "Ay", "Az"] print( columnar(vec_str, headers, max_column_width=18, min_column_width=18)[:-1]) headers = ["roll", "pitch", "yaw"] print( columnar(axis_rots_strs, headers, max_column_width=18, min_column_width=18))
def listtask(openfile=open): """ Print the todofile with filters or not """ empty = True headers = ["index", "task", "tags"] data = [] with openfile(todofilefromconfig(), "r") as todofile: for line in todofile.readlines(): # without filter -> we print all display = True if compute_args().filter: for tagtofilter in compute_args().filter: # regex to search tags "#toto " or "#toto" at the end of the line if not re.findall( " #" + re.escape(tagtofilter) + REGEX_SPACE_OR_ENDLINE, line.rstrip("\n"), ): display = False if compute_args().exclude: for tagtoexclude in compute_args().exclude: # regex to search tags "#toto " or "#toto" at the end of the line if re.findall( " #" + re.escape(tagtoexclude) + REGEX_SPACE_OR_ENDLINE, line.rstrip("\n"), ): display = False if compute_args().warning: isalert = False for part in line.split(): if (part.startswith("#") and part in listalerttags() or test_date(part[1:]) == "alert" or test_date(part[1:]) == "warning"): isalert = True if isalert == False: display = False if display: data.append(printlinetodo(line)) empty = False if empty: if compute_args().filter: printwarning("the filtered todolist is empty") else: printwarning("the todolist is empty") else: if compute_args().condensate: table = columnar(data, no_borders=True, wrap_max=0) else: if (read_config_boolean("FONCTIONAL", "condensate", "False") == "True"): table = columnar(data, no_borders=True, wrap_max=0) else: table = columnar(data, headers, no_borders=False, wrap_max=0) print(table)
def rate(self): conn = sqlite3.connect('project.db') c = conn.cursor() #c.execute('CREATE TABLE IF NOT EXISTS InvoiceInfo(HalfDayRate NOT NULL, FullDayRate NOT NULL, InsuranceHalfDay NOT NULL, InsuranceFullDay NOT NULL, TotalAmount NOT NULL)') c.execute('SELECT * FROM MyToolsInfo') rows = c.fetchall() if rows: for price in rows: self.halfday_rate = price[4] self.insurance_halfday_rate = 0.5 * self.halfday_rate self.total_halfday_rate = self.halfday_rate + self.insurance_halfday_rate self.fullday_rate = price[5] self.insurance_fullday_rate = 0.5 * self.fullday_rate self.total_fullday_rate = self.fullday_rate + self.insurance_fullday_rate prices = [ ['Half day rate\t', self.halfday_rate], ['Half day insurance rate\t', self.insurance_halfday_rate], ['Total Halfday invoice\t', self.total_halfday_rate], ['******************************', '*********************'], ['Full day rate\t', self.fullday_rate], ['Full day insurance rate\t', self.insurance_fullday_rate], ['Total fullday invoice\t', self.total_fullday_rate] ] print(columnar(prices)) else: print("You have no pending bill")
def __call__(self): # Url construction if not self.server_url.endswith('/'): self.server_url += '/' urlParams = 'package?search=' + self.keyword url = urllib.parse.urljoin(self.server_url, urlParams) r = re.get(url, allow_redirects=True) jsonResponse = json.loads(r.text) # Check if there is data for current search if jsonResponse['data']: headers = ['Package name', 'Description', 'Date', 'Created by'] data = [] for item in jsonResponse['data']: data.append([ item['name'], item['description'], item['createdAt'], item['user']['username'] if 'user' in item else '' ]) table = columnar(data, headers, no_borders=True) print(table) else: print("No match found for: " + self.keyword)
def view_profile(self): conn = sqlite3.connect('project.db') c = conn.cursor() c.execute('SELECT * FROM UserInfo') conn.commit() value = c.fetchall() if value: for elem in value: data = [["FirstName:\t ", elem[0]], ["LastName:\t ", elem[1]], ["UserName:\t ", elem[2]]] print(columnar(data)) choice = input( "\nPress Enter or any key to redirect back to Home Page!! " ) if choice == "": self.insurance_home() else: self.insurance_home() else: print("\nNo accounts are registered!!") choice = input( "\nPress Enter or any key to redirect back to Home Page!! ") if choice == "": self.insurance_home() else: self.insurance_home()
def print_table(data, headers, verbose, l): if verbose and len(data) != 0 and not l: table = columnar(data, headers, no_borders=True, \ patterns=patterns, row_sep='-') print(table) else: return
def xp_in_last_x_days(df, x, restricted_categories): first_date = df.loc[0][0] headers = ['Date', 'Day', 'XP'] data = [] total_xp = 0 today = datetime.now() for i in range(x - 1, -1, -1): date = today - timedelta(days=i) #Prevents the loop from executing before the first date if date < first_date: continue xp = xp_per_day(df, date, restricted_categories) total_xp += xp data.append([date.strftime('%d-%m-%Y'), date.strftime('%A'), str(xp)]) if len(data) == 0: nothing_found() return table = columnar(data, headers) print(table) print(f"F**k yeah you earned {total_xp}XP in the last {x} days!!!") plt.plot(np.flip(np.array(data)[:, 2].astype(int)), marker='o') plt.xlabel("Days previous to today") plt.ylabel("Carrots") plt.show()
def os(ctx, category, base): """ List all os inventoried on rawsec, you can add category.\n full documentation: https://rawsec-cli.readthedocs.io/ \f :param ctx: click context :param str category: :param str base: :return: """ wanted_keys = ["os", "base", "description", "link"] if category and category not in getOperatingCategory(json=ctx.obj["json"]): click.echo("Category available:") for category in getOperatingCategory(json=ctx.obj["json"]): click.echo(f"\t{category}") sys.exit("Not a good category") if category: if category == "project_transferred": wanted_keys = ["from", "to"] projects = getOperatingByCategory(ctx.obj["json"], category) else: projects = getAllOperating(ctx.obj["json"]) projects = [ {k: os[k] if k in os else "" for k in wanted_keys} for os in projects ] if base: projects = [ os for os in projects if os["base"].lower() == base.lower() ] projects = [list(project.values()) for project in projects] table = columnar(projects, headers=wanted_keys) click.echo(table) click.echo("Total projects found: " + str(len(projects)))
def cmd_create_session(args, _): release_tree = simics.ReleaseTree() if not args.version: versions = release_tree.get_platform_versions( args.platform, args.simics_version, ) version = versions[-1] else: version = args.version session_manager = K8SessionManager.getInstance() if not session_manager.is_valid_os(args.os): logging.warning('not valid OS: %s', args.os) service_info = session_manager.create_session( session_type='simulation', platform=args.platform, simics_version=args.simics_version, version=version, host_os=args.os ) name, host_port, created = service_info headers = ["Session Name", "Host OS", "VNC Address"] data = [[name, args.os, host_port]] table = columnar(data, headers, no_borders=True) print(table) if platform.system() == 'Windows': path_vnc = pathlib.Path('C:/Program Files/RealVNC/VNC Viewer/vncviewer.exe') if path_vnc.exists(): command = f'"{path_vnc}" {host_port}' popen = sp.Popen(shlex.split(command), shell=True)
def stuff(self): if self.weapon is None and self.panoply is None: print('You do not have any equipment at the moment.') else: L = list() if self.weapon is not None: l1 = list() l1.extend([ 'WEAPON', self.weapon.name, worldItems[self.weapon.name][DAMAGE], 'N/A', worldItems[self.weapon.name][DESC] ]) L.append(l1) if self.panoply is not None: l2 = list() l2.extend([ 'PANOPLY', self.panoply.name, 'N/A', worldItems[self.panoply.name][DEFENSE], worldItems[self.panoply.name][DESC] ]) L.append(l2) headers = ['TYPE', 'NAME', 'DAMAGE', 'DEFENSE', 'ABOUT'] print(columnar(L, headers, no_borders=True))
def ShowAgents(sensors): """ List all the agents registered in Tetration Appliance Hostname | UUID| Agent Type | Last checkin | Install Date | Version | Scopes """ columns = None if columns: headers = [] data_list = [] else: headers = [ 'Host Name', 'UUID', 'Agent Type', 'Last Check-in', 'Install Date', 'Version', 'Scopes' ] data_list = [[ x['host_name'], x['uuid'], x['agent_type'], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(x['last_config_fetch_at'])), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(x['created_at'])), x['current_sw_version'], ','.join(set([y['vrf'] for y in x['interfaces']])) ] for x in sensors['results']] table = columnar(data_list, headers, no_borders=False) print(table)
def getPlayerStatsBySeason(): try: player_id = int(input("Enter player id:")) season_year = input("Enter season year:") query = "SELECT PLAYER.player_name,minutes_played,goals,assists,clearances,tackles,red_cards,yellow_cards,saves FROM PLAYER INNER JOIN PLAYED_FOR ON PLAYER.player_id=%d AND season_year='%s'" % ( player_id, season_year) globals.cur.execute(query) result = globals.cur.fetchall() headers = [ "Name", "Minutes played", "Goals", "Assists", "Clearances", "Tackles", "Red cards", "Yellow cards", "Saves" ] data = [] for res in result: data.append(list(res.values())) if len(data) > 0: for i in range(1, len(data)): for j in range(1, 9): data[0][j] += data[i][j] data = data[0:1] table = columnar(data, headers) print(table) except Exception as e: print("Failed to retrieve from database") print(">>>>>>>>>>>>>", e) return False
def getAllPlayers(): try: query = "SELECT * FROM PLAYER" print(query) globals.cur.execute(query) result = globals.cur.fetchall() headers = [ 'Player ID', 'Name', 'DOB', 'Nationality', 'Agent Name', 'Positions' ] data = [] for res in result: agent_id = res["agent_id"] try: q = "SELECT name FROM AGENT WHERE agent_id=%d" % (agent_id) globals.cur.execute(q) res["agent_id"] = globals.cur.fetchone()["name"] except: res["agent_id"] = "" res["positions"] = getPositions(res["player_id"]) reslist = list(res.values()) data.append(reslist) table = columnar(data, headers) print(table) return True except Exception as e: globals.con.rollback() print("Failed to retrieve from database") print(">>>>>>>>>>>>>", e) return False
def parsHosts(hosts_table_rows): # iterating over each row of table and getting cells for row in hosts_table_rows: host = [] # finding all cells from table row cells = row.find_all("td") #iterating over each cell of row for cell in cells: # removing all child nodes from cell for child in cell.findChildren(): child.decompose() # appending cell values to dns_server list host.append(cell.get_text(' | ', strip=True)) DUMPSTER_HOSTS.append(host) if not len(DUMPSTER_HOSTS) == 0: dns_table = columnar(DUMPSTER_HOSTS, no_borders=True, min_column_width=2) print(dns_table) else: print("No Host Found")
def task1(plaintextfile, seeds): """ TASK 1: Generate ciphertext from input file, using geffes generator as the pseudorandom function / input :param plaintextfile: filename in string :param seeds: array of seeds for the three registers :return: ciphertext in array of bits """ global z1, z2, z3 print("[TASK1]: Initial setup of polynomials..") # set the key / seed values for the LFSR's (needs to be less than 2^(length of LFSR) # THis is the key!: z1.set_seed(seeds[0]) z2.set_seed(seeds[1]) z3.set_seed(seeds[2]) print("[TASK1]: Information about LFSRs:") data = [] for i, name in zip([z1, z2, z3], ["LFSR1", "LFSR2", "LFSR3"]): data.append([ name, i.get_polynomial(), str(bin(i.get_seed())[2:].ljust(i.get_degree(), '0')) + " " + f"({i.get_seed()})" ]) print( columnar(data, ["Id", "Polynomial", "Initial state"], no_borders=True)) c = [] print("[TASK1]: Generating ciphertext from", plaintextfile, "with Geffes generator") for y in bitgen(open(plaintextfile, "rb").read()): c.append( y ^ gg_combining_function(z1.next_o(), z2.next_o(), z3.next_o())) return c
def show_aps(args): print('\nScanning the available wireless spectrum...') aps_json = request_aps() # Generate a columnar table to show the APs info headers = [ 'rssi', 'essid', 'bssid', 'clients', 'encryption', 'auth', 'cipher' ] ap_data = [] for ap in aps_json: n_clients = len(ap['clients']) if not args.clients: ap_data.append([ str(ap['rssi']) + ' dBm', ap['hostname'], ap['mac'], n_clients, ap['encryption'], ap['authentication'], ap['cipher'] ]) elif args.clients and (n_clients > 0): ap_data.append([ str(ap['rssi']) + ' dBm', ap['hostname'], ap['mac'], n_clients, ap['encryption'], ap['authentication'], ap['cipher'] ]) if ap_data: ap_data.sort() ap_table = columnar.columnar(ap_data, headers, no_borders=True) print(ap_table)
def section5_2_3_t2(virtual_successes, ftps, header): print_output = [] return_output = [] print_output.append(header) prAGIfirst50 = [functions.forecast_generalized_laplace(failures=0, forecast_years=50, virtual_successes=virtual_successes, ftp=ftp) for ftp in ftps] prAGIfirst100 = [functions.forecast_generalized_laplace(failures=0, forecast_years=100, virtual_successes=virtual_successes, ftp=ftp) for ftp in ftps] prAGI2036 = [functions.four_param_framework_calendar(ftp, virtual_successes=virtual_successes) for ftp in ftps] prAGIfirst100 = [i * 100 for i in prAGIfirst100] prAGIfirst50 = [i * 100 for i in prAGIfirst50] prAGI2036 = [i * 100 for i in prAGI2036] prAGIfirst50_perc = round_sig(prAGIfirst50, 2) prAGIfirst100_perc = round_sig(prAGIfirst100, 2) prAGI2036_perc = round_sig(prAGI2036, 2) prAGIfirst50_str = round_sig(prAGIfirst50, 2, type=str) prAGIfirst100_str = round_sig(prAGIfirst100, 2, type=str) prAGI2036_str = round_sig(prAGI2036, 2, type=str) return_output.append(prAGIfirst50_perc) return_output.append(prAGIfirst100_perc) return_output.append(prAGI2036_perc) print_output.append(["pr(AGI in first 50 years)"] + [p + '%' for p in prAGIfirst50_str]) print_output.append(["pr(AGI in first 100 years)"] + [p + '%' for p in prAGIfirst100_str]) print_output.append(["pr(AGI by 2036 | no AGI by 2020)"] + [p + '%' for p in prAGI2036_str]) print(columnar(print_output, no_borders=True)) return return_output
def getAllCoaches(): try: query = "SELECT * FROM COACH" print(query) globals.cur.execute(query) result = globals.cur.fetchall() headers = ['Name', 'Manager Name', 'Nationality', 'Designation', 'DOB'] data = [] for res in result: try: q = "SELECT name FROM MANAGER WHERE manager_id=%d" % (res["manager_id"]) globals.cur.execute(q) res["manager_id"] = globals.cur.fetchone()["name"] except: res["manager_id"] = "" reslist = list(res.values()) data.append(reslist) table = columnar(data, headers) print(table) return True except Exception as e: globals.con.rollback() print("Failed to retrieve from database") print(">>>>>>>>>>>>>", e) return False
def list_users_long(): api_url = IDCS_END_POINT + "/admin/v1/Users?count=" + MAX_OBJECTS headers = { 'Content-Type': 'application/scim+json', 'Authorization': 'Bearer ' + TOKEN } r = requests.get(api_url, headers=headers) dict = r.json() list = dict['Resources'] table_headers = [ '====== USER NAME ======', 'ACTIVE', '====== USER ID ======', '==== TITLE ====', '==== CREATION DATE ====', '==== CREATED BY ====' ] table_list = [] for i in range(len(list)): print(list[i]['userName']) # sometimes, no title assigned, so no title key try: table_list.append([ list[i]['userName'], list[i]['active'], list[i]['id'], list[i]['title'], list[i]['meta']['created'], list[i]['idcsCreatedBy']['display'] ]) except: table_list.append([ list[i]['userName'], list[i]['active'], list[i]['id'], " ", list[i]['meta']['created'], list[i]['idcsCreatedBy']['display'] ]) # sort by creation date (oldest first) table = columnar(sorted(table_list, key=itemgetter(4)), table_headers, no_borders=True) print(table)
def ShowScopes(scopes): ScopesList = [] headers = ['Number', 'Scope Name', 'Scope ID', 'VRF ID'] for i, scope in enumerate(scopes): ScopesList.append([i + 1, scope["name"], scope["id"], scope['vrf_id']]) table = columnar(ScopesList, headers, no_borders=False) print(table)
def searchClub(): try: name = input("Enter search term:").strip() name = '%' + name + '%' query = "SELECT * FROM CLUB WHERE club_name LIKE '%s'" % name print(query) globals.cur.execute(query) result = globals.cur.fetchall() headers = [ 'Club ID', 'Name', 'Home Ground', 'Foundation Year', 'Street Address', 'Zip Code', 'City', 'Country' ] data = [] for res in result: try: q = "SELECT * FROM ZIP_MAP WHERE zip_code='%s'" % ( res["zip_code"]) globals.cur.execute(q) zip_map = globals.cur.fetchone() res["city"] = zip_map["city"] res["country"] = zip_map["country"] except: res["city"] = "" res["country"] = "" reslist = list(res.values()) data.append(reslist) table = columnar(data, headers) print(table) return True except Exception as e: globals.con.rollback() print("Failed to retrieve from database") print(">>>>>>>>>>>>>", e) return False
def reversals(): headers = [ "[STOCK]", "[STATUS]", "[CHANGE]", "[LAST]", "[OPEN]", "[HIGH]", "[LOW]", "[VOLUME]", "[LIQUIDITY]" ] my_reversals = [] os.chdir('/home/r3dux/code/python/projects/stocks/watchlists/') with open('./reversals.txt', 'r') as wl: for line in wl: ticker = str(line.replace('\n', '').upper()) ticker = f'{ticker}' open_price = f'${price_open(ticker)}' close_price = f'${price_close(ticker)}' high_price = f'${price_high(ticker)}' low_price = f'${price_low(ticker)}' total_volume = f'{volume(ticker):,} ' total_liquidity = f'{liquidity(ticker)} ' price_change = f'{change(ticker)} %' stock_status = f'{status(ticker)}' ticker = [ ticker, stock_status, price_change, low_price, open_price, high_price, close_price, total_volume, total_liquidity ] my_reversals.append(ticker) table = columnar(my_reversals, headers, no_borders=True, min_column_width=10) print("\nREVERSALS\n") print(table) print('\n')
def rate(self): conn = sqlite3.connect('project.db') c = conn.cursor() c.execute('SELECT * FROM MyToolsInfo') rows = c.fetchall() if rows: for price in rows: self.halfday_rate = price[4] self.insurance_halfday_rate = 0.5 * self.halfday_rate self.total_halfday_rate = self.halfday_rate + self.insurance_halfday_rate self.fullday_rate = price[5] self.insurance_fullday_rate = 0.5 * self.fullday_rate self.total_fullday_rate = self.fullday_rate + self.insurance_fullday_rate prices = [ ['Half day rate\t', self.halfday_rate], ['Half day insurance rate\t', self.insurance_halfday_rate], ['Total Halfday invoice\t', self.total_halfday_rate], ['******************************', '*********************'], ['Full day rate\t', self.fullday_rate], ['Full day insurance rate\t', self.insurance_fullday_rate], ['Total fullday invoice\t', self.total_fullday_rate] ] print(columnar(prices)) else: print("You have no pending bill")
def tabulate_data(self, data): """Take data in form of list and make a structured table.""" scr_width = shutil.get_terminal_size().columns max_col_width = (scr_width - 18) // 2 # df = pd.DataFrame(data) # df.columns = ['TRAIN', 'ARRIVE', 'DIR', 'TYPE', 'NOTES'] # return df.to_string( # formatters=self.format_align_left(df, ['TRAIN', 'NOTES']), # index=False, # justify="left", # max_colwidth=max_col_width) headers = ['TRAIN', 'ARRIVE', 'DIR', 'TYPE', 'NOTES'] justify = ['l', 'l', 'c', 'l', 'l'] table = columnar(data, headers, justify=justify, no_borders=True, max_column_width=max_col_width, wrap_max=8, terminal_width=scr_width, column_sep='') # convert to array table_array = str(table).split('\n') # drop first and third line table_array.pop(0) table_array.pop(1) # remove two spaces at beginning of each line for i in range(len(table_array)): table_array[i] = table_array[i][2:] # put back together again table = '\n'.join(table_array) return table
def get_top_scorers(json_data): scorers = json_data['scorers'] scorer_list = [] # Iterate through list of dictionaries to get player name, team and number of goals scored in a new dictionary object. for ele in scorers: scorer_details = {} scorer_details['player_name'] = ele['player']['name'] scorer_details['numberOfGoals'] = ele['numberOfGoals'] scorer_details['team'] = ele['team']['name'] scorer_list.append(scorer_details) # Get the top 5 goal scorers. # 1. Sort the list of dictionaries by the number of goals scored. sorted_list = sorted(scorer_list, key=lambda i: i['numberOfGoals'], reverse=True) top_goalscorers = [] num_goals = [] # 2. Print the player names, number of goals scored and their respective clubs for ele in sorted_list[:5]: top_goalscorers.append(ele['player_name']) num_goals.append(ele['numberOfGoals']) # convert data into list of lists to fit into the columnar function. data = [list(a) for a in zip(top_goalscorers, num_goals)] headers = ["Name", "Goals"] table = columnar(data, headers) return table
def getTransfersByPriceRange(): try: low = int(input("Enter minimum price:").strip()) high = int(input("Enter maximum price:").strip()) query = "SELECT PLAYER.player_name,CLUB_FROM.club_name,CLUB_TO.club_name,AGENT.name,transfer_fee,agent_fee,date_of_transfer\ FROM TRANSFER\ INNER JOIN PLAYER ON TRANSFER.player_id=PLAYER.player_id\ INNER JOIN CLUB CLUB_FROM ON TRANSFER.club_from_id=CLUB_FROM.club_id\ INNER JOIN CLUB CLUB_TO ON TRANSFER.club_to_id=CLUB_TO.club_id\ INNER JOIN AGENT ON TRANSFER.agent_id=AGENT.agent_id\ WHERE transfer_fee>=%d AND transfer_fee<=%d" % (low, high) globals.cur.execute(query) result = globals.cur.fetchall() headers = [ "Name", "From", "To", "Agent", "Transfer fee", "Agent Fee", "Transfer" ] data = [] for res in result: data.append(list(res.values())) table = columnar(data, headers) print(table) return True except Exception as e: globals.con.rollback() print("Failed to retrieve from database") print(">>>>>>>>>>>>>", e) return False
def print_stats(self) -> None: exercises = self.config["exercises"] weight = self.config["my_weight"] logging.debug(f"Exercises: {exercises}") logging.debug(f"Weight: {weight}") headers = [""] data = [] rms = ["1RM"] records = ["Record"] percents = ["1RM/weight"] for i in exercises: logging.debug(f"{i} - {exercises[i]}") headers.append(i.capitalize()) if exercises[i]["1RM"] == exercises[i]["max"]: rms.append( f"{attr('bold')+fg(2)}{round(exercises[i]['1RM'])}{attr('reset')}") else: rms.append(round(exercises[i]["1RM"])) percents.append(round(exercises[i]["1RM"]/weight, 2)) records.append(round(exercises[i]["record"])) data.append(rms) data.append(records) data.append(percents) table = columnar(data, headers, min_column_width=10, justify="c") print(table)
def parseMxServers(mx_servers_table_rows): # iterating over each row of table and getting cells for row in mx_servers_table_rows: mx_server = [] # finding all cells from table row cells = row.find_all("td") #iterating over each cell of row for cell in cells: # removing all child nodes from cell for child in cell.findChildren(): child.decompose() # appending cell values to dns_server list mx_server.append(cell.get_text(strip=True)) DUMPSTER_MX_SERVERS.append(mx_server) # checking if any mx server found if not len(DUMPSTER_MX_SERVERS) == 0: mx_table = columnar(DUMPSTER_MX_SERVERS, no_borders=True, min_column_width=2, row_sep='-') print(mx_table) else: print("No MX Server Found")