async def execute(self, message: discord.Message, args: list, keys: DotDict) -> CommandResult: sql_query = message.content[len(cmd_prefix + self.name) + 1:] with connection.cursor() as c: try: c.execute(sql_query) except Exception as e: raise CommandException( error=type(e).__name__ + ": " + str(e), title="Произошла ошибка при выполнении SQL") if "commit" in keys: connection.commit() desc = c.description if desc is None: return CommandResult.success fields = [field[0] for field in desc] results = c.fetchall() tbl = BeautifulTable(max_width=64) tbl.column_headers = fields for result in results: tbl.append_row(result) embed = self.bot.get_special_embed( title="Результат выполнения SQL запроса", description="```%s```" % tbl, color=0xb63a6b) if not results: embed.description = "Нет результатов." embed.color = 0xFF4C4C await message.channel.send(embed=embed) return CommandResult.success
def print_table(table, title_list): """ Prints table with data. Example: /-----------------------------------\ | id | title | type | |--------|----------------|---------| | 0 | Counter strike | fps | |--------|----------------|---------| | 1 | fo | fps | \-----------------------------------/ Args: table (list): list of lists - table to display title_list (list): list containing table headers Returns: None: This function doesn't return anything it only prints to console. """ from beautifultable import BeautifulTable beautiful_table = BeautifulTable() beautiful_table.column_headers = title_list for row in table: beautiful_table.append_row(row) print(beautiful_table)
def ec2info(ctx, instance_name_search): """ instance_info NAME Prints out the instance(s) that match NAME. \f :param ctx: :return: """ c = control.AControl() instances = c.find_instances(instance_name_search) formatted = c.filter_instance_data_human(instances) table = BeautifulTable(max_width=200) # In order of output: columns = [ 'Name', 'PrivateIpAddress', 'InstanceType', 'InstanceAge', 'InstanceId', 'Squad', 'State', 'InfoLink' ] table.column_headers = columns for f in formatted: f['InfoLink'] = 'https://www.ec2instances.info/?filter=' + f[ 'InstanceType'] output_l = [] for c in columns: output_l.append(f[c]) table.append_row(output_l) table.sort('Name') table.set_style(BeautifulTable.STYLE_COMPACT) click.echo(table)
def test_display_challenge_details(self): table = BeautifulTable(max_width=200) attributes = [ "description", "submission_guidelines", "evaluation_details", "terms_and_conditions" ] column_attributes = [ "Start Date", "End Date", "Description", "Submission Guidelines", "Evaluation Details", "Terms and Conditions" ] table.column_headers = column_attributes values = [] start_date = convert_UTC_date_to_local( self.challenge_data["start_date"]).split(" ")[0] end_date = convert_UTC_date_to_local( self.challenge_data["end_date"]).split(" ")[0] values.extend([start_date, end_date]) values.extend( list( map(lambda item: clean_data(self.challenge_data[item]), attributes))) table.append_row(values) expected = str(table) runner = CliRunner() result = runner.invoke(challenge, ["1"]) response = result.output.strip() assert response == expected
def test_display_my_submission_details_with_end_date_and_start_date(self): table = BeautifulTable(max_width=100) attributes = [ "id", "participant_team_name", "execution_time", "status" ] columns_attributes = [ "ID", "Participant Team", "Execution Time(sec)", "Status", "Submitted At", "Method Name" ] table.column_headers = columns_attributes start_date = datetime.strptime('6/5/18', "%m/%d/%y") end_date = datetime.strptime('6/9/18', "%m/%d/%y") for submission in self.submissions: date = validate_date_format(submission['submitted_at']) if (date >= start_date and date <= end_date): # Check for empty method name date = convert_UTC_date_to_local(submission['submitted_at']) method_name = submission["method_name"] if submission[ "method_name"] else "None" values = list(map(lambda item: submission[item], attributes)) values.append(date) values.append(method_name) table.append_row(values) output = str(table).rstrip() runner = CliRunner() result = runner.invoke( challenge, ['3', 'phase', '7', 'submissions', '-s', '6/5/18', '-e', '6/9/18']) response = result.output.rstrip() assert response == output
def hours_as_table(content, current_month, full, show_weekday): """ Validates that you can actually use the configured project. """ table = BeautifulTable() if full: column_headers = ["Date", "Hours", "Project", "Assigment Type", "Description"] else: column_headers = ["Date", "Description"] if show_weekday: column_headers = ["Weekday"] + column_headers table.column_headers = column_headers rows = content.find(class_='tbl-respuestas').find_all('tr') for row in rows[:-1]: cols = row.find_all('td') if cols: date = cols[0].string if not current_month else cols[0].string[:2] if full: values = [date, cols[1].string, cols[2].string, cols[3].string, cols[4].string] else: values = [date, cols[4].string] if show_weekday: weekday = datetime.strptime(cols[0].string, r'%d/%m/%Y').weekday() values = [WEEKDAYS[weekday]] + values table.append_row(values) if full: values = ["" for i in range(len(column_headers))] values[column_headers.index("Hours")] = rows[-1].find_all('td')[1].string if len(rows[-1].find_all('td')) > 1 else 0.0 table.append_row(values) return table
def pretty_print_challenge_details(challenge): table = BeautifulTable(max_width=200) attributes = [ "description", "submission_guidelines", "evaluation_details", "terms_and_conditions", ] table.column_headers = [ "Start Date", "End Date", "Description", "Submission Guidelines", "Evaluation Details", "Terms and Conditions", ] values = [] start_date = convert_UTC_date_to_local( challenge["start_date"]).split(" ")[0] end_date = convert_UTC_date_to_local(challenge["end_date"]).split(" ")[0] values.extend([start_date, end_date]) values.extend( list(map(lambda item: clean_data(challenge[item]), attributes))) table.append_row(values) echo(table)
def main(): parser = argparse.ArgumentParser( description='Attempt to locate subsidiaries of an organization') parser.add_argument('-c', metavar='COMPANY', required=False, help='Canonical company name') parser.add_argument('-w', metavar='ID', required=False, help='WikiData entity ID') parser.add_argument('-i', metavar='INPUT', required=False, help='Supplemental input file of subsidiaries') parser.add_argument('-o', metavar='OUTPUT', required=False, help='Output file location') args = parser.parse_args() config = read_config() table = BeautifulTable() table.column_headers = ['Name', 'Domain', 'Source'] subsidiaries = [] if not os.path.exists('organizations.csv'): download_crunchbase_odm(config['crunchbase_odm_key']) load_crunchbase_odm() if args.c is not None: company = args.c cw_id = cw_get_company_by_name(company) if cw_id is not None: subsidiaries.extend(cw_get_child_companies(cw_id)) if args.w is not None: wikidata_id = args.w for row in wikidata_resolve(wikidata_id): table.append_row(row) if args.i is not None: with open(args.i, 'r') as input_file: subsidiaries.extend(map(str.strip, input_file.readlines())) for row in try_resolve_names(subsidiaries, config): table.append_row(row) if args.o is not None: with open(args.o, 'w') as output_file: output_writer = csv.writer(output_file, quoting=csv.QUOTE_MINIMAL) for row in table: output_writer.writerow(list(row)) if len(table) == 0: sys.stderr.write('[-] Error, no subsidiaries identified for "%s"\n' % company) print(table)
def do_l(self, arg): 'Lists current portfolio' portfolio = self.trader.portfolios() print 'Equity Value:', portfolio['equity'] account_details = self.trader.get_account() if 'margin_balances' in account_details: print 'Buying Power:', account_details['margin_balances'][ 'unallocated_margin_cash'] positions = self.trader.securities_owned() symbols = [] for position in positions['results']: symbol = self.get_symbol(position['instrument']) symbols.append(symbol) raw_data = self.trader.quotes_data(symbols) quotes_data = {} for quote in raw_data: quotes_data[quote['symbol']] = quote['last_trade_price'] table = BeautifulTable() table.column_headers = [ "symbol", "current price", "quantity", "total equity" ] for position in positions['results']: quantity = int(float(position['quantity'])) symbol = self.get_symbol(position['instrument']) price = quotes_data[symbol] total_equity = float(price) * quantity table.append_row([symbol, price, quantity, total_equity]) print(table)
def menu_travel(): '''Prints list with destinations and respective time of flight Arguments: None Returns: int: new city and travel time''' #print welcome to Employee Travel Service global current_location destinations_times = game_data.keys() list_with_destinations = [place[0] for place in destinations_times] #extracts the cities from the (city, time) tuple and creates a list travel_table = BeautifulTable() #creates a new table travel_table.column_headers = ['Destination', 'Flight Duration'] for destination, ttime in game_data.keys(): travel_table.append_row([destination, ttime]) travel_table.append_column('Flight #', ['1711', '1931']) print travel_table users_location = (raw_input('What is your next destination? (Type city name)\n')).title() #gets user input on next destination if users_location not in list_with_destinations: print 'Invalid Choice' else: current_location = users_location#if the location is on the list, prints the destination and updates the variable current_location print 'Your reservations have been confirmed to {} on Flight # . Enjoy the in-flight meal.'.format(current_location) print current_location #city
def do_o(self, arg): 'List open orders' open_orders = self.trader.get_open_orders() if open_orders: table = BeautifulTable() table.column_headers = [ "index", "symbol", "price", "quantity", "type", "id" ] index = 1 for order in open_orders: if order['trigger'] == 'stop': order_price = order['stop_price'] order_type = "stop loss" else: order_price = order['price'] order_type = order['side'] + " " + order['type'] table.append_row([ index, self.get_symbol(order['instrument']), order_price, int(float(order['quantity'])), order_type, order['id'], ]) index += 1 print(table) else: print "No Open Orders"
async def command_list(self, ctx: Context): try: core = self.get_commandlist() cmd = core.command count = core.count proc = core.process count, cmd, proc = (list(t) for t in zip(*sorted(zip(count, cmd, proc), reverse=True))) p = BeautifulTable() p.set_style(STYLE_BOX_ROUNDED) p.rows.separator = "" p.column_headers = ["*", "Command", "Count", "Process"] z = 0 for x in range(25): try: z += 1 p.append_row([x + 1, cmd[x], f'{count[x]:,}', f"{round(proc[x], 2)}"]) except (IndexError, RuntimeError): z -= 1 break post = Embed(color=await ctx.guildcolor()) post.title = f"Naila's top {z} commands:" post.description = f"```ml\n{p}```" await ctx.reply(embed=post) except ValueError: return await ctx.send_error("Unable to post stats, Not enough data!")
def text_report(*orders): ''' Generate a report suitable for viewing as just text on a screen ''' table = BeautifulTable() table.column_headers = [ 'Order Id', 'Order Type', 'Title', 'Order Amount', 'Purchase Date', ] for order in orders: table.append_row( [ order.AmazonOrderId, order.OrderType, order.OrderItem.Title, order.OrderTotal.Amount if 'OrderTotal' in order.keys() else 'N/A', order.PurchaseDate, ] ) table.sort('Purchase Date') return table
def print(self, title: str = None): table = BeautifulTable() table.append_row(self.items[0:3]) table.append_row(self.items[3:6]) table.append_row(self.items[6:9]) print(title if title is not None else 'State %s' % self.id) print(table)
def print_table(data, headers): t_width, _ = shutil.get_terminal_size() if t_width >= 95: table = BeautifulTable(max_width=95, default_alignment=ALIGN_LEFT) else: table = BeautifulTable(max_width=t_width, default_alignment=ALIGN_LEFT) table.column_headers = headers # Convert dictionary data to list for fuse, details in data.items(): row = [ "{}\n({})".format(fuse, details["descr"]), details["value_descr"], details["value"], details["mask"] ] table.append_row(row) # change table style table.set_style(BeautifulTable.STYLE_BOX_ROUNDED) table.header_separator_char = '═' table.intersect_header_left = '╞' table.intersect_header_mid = '╪' table.intersect_header_right = '╡' # Print table print("{}\n".format(table))
def get_all_firmware(self, module_id: int): logging.info(self.__class__.__name__ + ":" + inspect.currentframe().f_code.co_name) # Get number of module in the partition req_str_chassis = "http://" + self.bmc_ip + ":8080/redfish/v1/Chassis" self.min_module_nb = 0 self.max_module_nb = self.get_modules_number() if module_id != 9999: self.min_module_nb = module_id self.max_module_nb = module_id + 1 print(" end thr2 " + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) sys.stdout.write("Getting firmwares info ") sys.stdout.flush() with concurrent.futures.ThreadPoolExecutor( max_workers=self.max_module_nb) as mod_executor: future_mods = { mod_executor.submit(self.thread_get_module_firmwares, id): id for id in range(self.min_module_nb, self.max_module_nb) } table = BeautifulTable() table.set_style(BeautifulTable.STYLE_GRID) fw_column_header = ["Component"] for module in range(self.min_module_nb, self.max_module_nb): fw_column_header.append("Module " + str(module)) table.append_row(fw_column_header) for key_name in sorted(self.modules_firmwares.keys()): table.append_row(self.modules_firmwares[key_name]) print("") print(table) print(" end thr2 " + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
def get_followers_profile(twitter_api, screen_names=None, user_ids=None): assert (screen_names != None) != (user_ids != None), \ "Must have screen_names or user_ids, but not both" table = BeautifulTable() table.column_headers = [ "NOMBRE", "SCREEN NAME", "UBICACION", "NUM SEGUIDORES" ] items_to_info = {} items = screen_names or user_ids while len(items) > 0: items_str = ','.join([str(item) for item in items[:100]]) items = items[100:] if screen_names: response = make_twitter_request(twitter_api.users.lookup, screen_name=items_str) else: # user_ids response = make_twitter_request(twitter_api.users.lookup, user_id=items_str) print 'tus seguidores son: ' for key in response: #print "nombre: " + key['name'] + "| su twitter es: " + key['screen_name'] + #"| ubicacion: "+ key['location'] + "seguidores: " + str(key['followers_count']) name = key['name'] screen_name = key['screen_name'] location = key['location'] seguidores = key['followers_count'] table.append_row([ name.encode('utf-8'), screen_name.encode('utf-8'), location.encode('utf-8'), seguidores ]) print table
def pretty_print_challenge_data(challenges): """ Function to print the challenge data """ table = BeautifulTable(max_width=200) attributes = ["id", "title", "short_description"] columns_attributes = [ "ID", "Title", "Short Description", "Creator", "Start Date", "End Date", ] table.column_headers = columns_attributes for challenge in reversed(challenges): values = list(map(lambda item: challenge[item], attributes)) creator = challenge["creator"]["team_name"] start_date = convert_UTC_date_to_local(challenge["start_date"]) end_date = convert_UTC_date_to_local(challenge["end_date"]) values.extend([creator, start_date, end_date]) table.append_row([ colored(values[0], 'white'), colored(values[1], 'yellow'), colored(values[2], 'cyan'), colored(values[3], 'white'), colored(values[4], 'green'), colored(values[5], 'red'), ]) echo(table, color='yes')
async def get_war_log(self, ctx): warLog = [] tempWarLog = await self.bot.coc.get_warlog(ROYALS_TAG) i = 0 while i < 7: warLog.append(tempWarLog[i]) i += 1 losecnt = 0 table = BeautifulTable() table.column_headers = ["Win/Lose", "Enemy"] # iterate over the wars for war in warLog: table.append_row([war.result, war.opponent.name]) if war.result == "lose": losecnt += 1 table.set_style(BeautifulTable.STYLE_COMPACT) print(f"loses: {losecnt}") await ctx.send(table)
def new_board(): from beautifultable import BeautifulTable board = BeautifulTable() board.append_row(['1', '2', '3']) board.append_row(['4', '5', '6']) board.append_row(['7', '8', '9']) print(board, '\n')
def setup(self): challenge_data = json.loads(challenge_response.challenges) url = "{}{}" responses.add(responses.GET, url.format("https://evalapi.cloudcv.org", URLS.challenge_list.value), json=challenge_data, status=200) self.output = "" challenge_data = challenge_data["results"] table = BeautifulTable(max_width=200) attributes = ["id", "title", "short_description"] columns_attributes = [ "ID", "Title", "Short Description", "Creator", "Start Date", "End Date" ] table.column_headers = columns_attributes for challenge_json in reversed(challenge_data): values = list(map(lambda item: challenge_json[item], attributes)) creator = challenge_json["creator"]["team_name"] start_date = convert_UTC_date_to_local( challenge_json["start_date"]) end_date = convert_UTC_date_to_local(challenge_json["end_date"]) values.extend([creator, start_date, end_date]) table.append_row(values) self.output = str(table)
def test_display_participant_teams_list(self): table = BeautifulTable(max_width=200) attributes = ["id", "team_name", "created_by"] columns_attributes = [ "ID", "Team Name", "Created By", "Members", "Team URL", ] table.column_headers = columns_attributes for team in self.participant_teams: values = list(map(lambda item: team[item], attributes)) members = ", ".join( map(lambda member: member["member_name"], team["members"]) ) values.append(members) if team["team_url"]: values.append(team["team_url"]) else: values.append("None") table.append_row(values) output = str(table) runner = CliRunner() result = runner.invoke(teams, ["--participant"]) response = result.output.rstrip() assert response == output
def table(model_list, nmodel, accuracies, precisions, recalls, f1_scores, accuracies_dev): table = BeautifulTable() table.column_headers = ["{}".format(model_list[nmodel]), "Avg", "Stdev"] table.append_row([ "Accuracy", round(np.average(accuracies), 3), round(np.std(accuracies), 3) ]) table.append_row([ "Precision", round(np.average(precisions), 3), round(np.std(precisions), 3) ]) table.append_row( ["Recall", round(np.average(recalls), 3), round(np.std(recalls), 3)]) table.append_row([ "F1_score", round(np.average(f1_scores), 3), round(np.std(f1_scores), 3) ]) table.append_row([ "Accuracy_dev", round(np.average(accuracies_dev), 3), round(np.std(accuracies_dev), 3) ]) print(table)
def display_files_from_drive(count, items): # items = results.get('files', []) file_names = [] modified_times = [] counts = [] table = BeautifulTable(max_width=160) table.column_headers = ["File Number", "File Name", "Last Modified Time"] if not items: print('No files found.') else: print('Files:') for item in items: modified_time = item.get('modifiedTime', 'n/a') file_names.append(item['name']) modified_times.append(modified_time) #print(u'{0} ({1}) : last modified {2} \n \n'.format(item['name'], item['id'], modified_time)) table.append_row([ colored(count, 'magenta'), colored(item['name'] + " ", 'green'), colored( modified_time + " ", 'red') ]) count += 1 print(table) del table[-1] time.sleep(.3) return count
def evaluate(): totals = dict() print('PLease wait untill finishing Summary....^_^') for f in r: if openAndCount(f) is not None: name, fileBefore, blank, nAfter = openAndCount(f) else: continue ext = name[name.find('.') + 1:] c = totals.get(ext, (0, 0)) # print(type(c)) pure, blankTotal = c pure += nAfter blankTotal += blank totals[ext] = (pure, blankTotal) from beautifultable import BeautifulTable table = BeautifulTable() table.column_headers = ["Extension", "Blank Line", "Pure Code"] for ext, c in totals.items(): pure, blank = c if len(ext) > 10: continue table.append_row([ext, blank, pure]) if len(table) == 0: print('No Code Files Found') return print(table)
def pretty_print_team_data(teams, is_host): """ Function to print the team data """ table = BeautifulTable(max_width=200) attributes = ["id", "team_name", "created_by"] columns_attributes = [ "ID", "Team Name", "Created By", "Members", "Team URL", ] table.column_headers = columns_attributes for team in teams: values = list(map(lambda item: team[item], attributes)) if is_host: members = ", ".join( map(lambda member: member["user"], team["members"])) else: members = ", ".join( map(lambda member: member["member_name"], team["members"])) values.append(members) if team["team_url"]: values.append(team["team_url"]) else: values.append("None") table.append_row(values) echo(table)
def _generate_statistics_table(self) -> str: """ Generate a table with an overview of basic stats for each database. """ table = BeautifulTable(default_alignment=BeautifulTable.ALIGN_RIGHT) table.column_headers = [ 'source', 'total obj', 'rt obj', 'aut-num obj', 'serial', 'last export' ] table.column_alignments['source'] = BeautifulTable.ALIGN_LEFT table.left_border_char = table.right_border_char = '' table.right_border_char = table.bottom_border_char = '' table.row_separator_char = '' table.column_separator_char = ' ' for status_result in self.status_results: source = status_result['source'].upper() total_obj, route_obj, autnum_obj = self._statistics_for_source( source) serial = status_result['serial_newest_seen'] last_export = status_result['serial_last_export'] if not last_export: last_export = '' table.append_row([ source, total_obj, route_obj, autnum_obj, serial, last_export ]) total_obj, route_obj, autnum_obj = self._statistics_for_source(None) table.append_row(['TOTAL', total_obj, route_obj, autnum_obj, '', '']) return str(table)
def create_table(rows, order, style): """ Create table for display :param list rows: table rows :param str order: table sorted order :param str style: table style :return: table for display :rtype: BeautifulTable """ table = BeautifulTable() table.column_headers = ["name", "license"] table.column_alignments["name"] = BeautifulTable.ALIGN_LEFT table.column_alignments["license"] = BeautifulTable.ALIGN_LEFT if style == "markdown": table.set_style(BeautifulTable.STYLE_MARKDOWN) elif style == "rst": table.set_style(BeautifulTable.STYLE_RESTRUCTURED_TEXT) else: table.set_style(BeautifulTable.STYLE_COMPACT) for row in rows: table.append_row(row) if order == "license": table.sort("license") return table
def test_display_my_submission_details(self): table = BeautifulTable(max_width=100) attributes = [ "id", "participant_team_name", "execution_time", "status" ] columns_attributes = [ "ID", "Participant Team", "Execution Time(sec)", "Status", "Submitted At", "Method Name" ] table.column_headers = columns_attributes for submission in self.submissions: # Format date date = datetime.strptime(submission['submitted_at'], "%Y-%m-%dT%H:%M:%S.%fZ") from_zone = tz.tzutc() to_zone = tz.tzlocal() # Convert to local timezone from UTC. date = date.replace(tzinfo=from_zone) converted_date = date.astimezone(to_zone) date = converted_date.strftime('%D %r') # Check for empty method name method_name = submission["method_name"] if submission[ "method_name"] else "None" values = list(map(lambda item: submission[item], attributes)) values.append(date) values.append(method_name) table.append_row(values) output = str(table).rstrip() runner = CliRunner() result = runner.invoke(challenge, ['3', 'phase', '7', 'submissions']) response = result.output.rstrip() assert response == output
def mostrartablaTTgrupo(): teams = [] jugadores = [] scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name( 'CEMK-0ed44d25f869.json', scope) gc = gspread.authorize(credentials) wks = gc.open("TTMontewario").sheet1 val = wks.get_all_values() val.sort(key=lambda x: x[3]) table = BeautifulTable() table.column_headers = ["Equipo", "Tiempo"] for x in range(0, len(val) - 1): if not str(val[x][2]) in [x[0] for x in teams]: teams.append([str(val[x][2]), int(val[x][3]), 0]) jugadores.append(str(val[x][1])) else: indice = [x[0] for x in teams].index(str(val[x][2])) if (teams[indice][2] < 2 and not str(val[x][1]) in jugadores): entero = int(teams[indice][1]) teams[indice][1] = sumatiempos(entero, val[x][3]) teams[indice][2] += 1 jugadores.append(str(val[x][1])) print(teams) teams.sort(key=lambda x: x[1]) for x in range(0, len(teams)): table.append_row([str(teams[x][0]), str(cargar(teams[x][1]))]) return table
def text(self): totals = summary_template.format( self.compiled_result['counts']['total'], self.compiled_result['counts']['valid'], self.compiled_result['counts']['failed'], self.compiled_result['counts']['fatal'] ) ssl_info = 'No valid SSL certificate detected' if self.compiled_result['network']['ssl']: ssl_info = 'Valid SSL certificate detected' network = network_template.format( ssl_info, self.compiled_result['network']['average_ttl'] ) try: max_columns = int(subprocess.check_output(['stty', 'size']).split()[1]) except Exception: max_columns = 80 entities = '' for entity, messages in self.compiled_result['object_messages'].items(): table = BeautifulTable(max_columns) table.column_headers = ['', 'severity', 'message', 'occurences'] entity_list = '' message_key = 1 for message in messages: message = self.compiled_result['object_messages'][entity][message] row = [] row.append(message_key) row.append(message['severity']) row.append(message['message']) row.append(message['count']) for object in message['objects']: entity_list += '[{}] {},\n'.format(message_key, object) table.append_row(row) message_key += 1 entities += '# {}\n{}\n\nAffected Entities:\n\n{}\n\n'.format(entity, table, entity_list[:-2]) return 'Validation Result:\n\n{}\n{}\n{}'.format(totals, network, entities[:-2])
def distribution_process(distribution, dist_class): increase = defaultdict(int) decrease = defaultdict(int) same = defaultdict(int) category = dict({'nao_eleitos': defaultdict(int), 'reeleitos': defaultdict(int), 'novos': defaultdict(int)}) total = defaultdict(int) for cond, dep in distribution.items(): for d, val in dep.items(): total[cond] += 1 before, election = dist_dep(val) ks = ks_2samp(before, election) # reject null hypotesis if ks[1] < 0.05: if np.mean(before) < np.mean(election): increase[cond] += 1 else: decrease[cond] += 1 else: same[cond] += 1 print(dist_class) table = BeautifulTable() table.column_headers = ["","RE", "LS", "NC", "total"] table.append_row("increase", increase["reeleitos"], increase["nao_eleitos"], increase["novos"], (increase["reeleitos"] + increase["nao_eleitos"] + increase["novos"])) table.append_row("maintained",same["reeleitos"], same["nao_eleitos"], same["novos"],(same["reeleitos"] + same["nao_eleitos"] + same["novos"])) table.append_row("decrease",decrease["reeleitos"], decrease["nao_eleitos"], decrease["novos"], (decrease["reeleitos"] + decrease["nao_eleitos"] + decrease["novos"])) table.append_row("total",(decrease["reeleitos"]+same["reeleitos"]+decrease["reeleitos"]), (decrease["nao_eleitos"]+same["nao_eleitos"]+decrease["nao_eleitos"]), (decrease["novos"]+same["novos"]+decrease["novos"]) ) print(table)
print timeO urls = [] for i in range(int(count)): temp = raw_input('Enter URL:') print temp urls.append(temp) j = 0 k = 0 table = BeautifulTable() table.column_headers = ["Current Time Stamp", "Status", "URL","Response Time","Reason For Failure"] while j < len(urls): ts = time.time() try: response = requests.get(urls[j], timeout=float(timeO)) response.raise_for_status() table.append_row([ts,response.status_code, urls[j], response.elapsed.total_seconds(), "NA"]) j += 1 except requests.exceptions.ConnectionError as e: k += 1 print(k) if (k>=3): #table.append_row([ts,"Connection Exception", urls[j], "0", e]) table.append_row([ts,"Connection Exception", urls[j], time.time() - ts, e]) k = 0 j += 1 continue except requests.exceptions.Timeout as e: table.append_row([ts,"Timeout Exception", urls[j], "0", e]) j += 1 continue except requests.exceptions.HTTPError as e:
def select(self, publications: List[Publication]) -> Publication: """ Print the search results and asks the user to choose one to download. :param publications: list of Publication :returns: a Publication """ preferred_order = [ 'id', 'title', 'authors', 'pages', 'extension', 'size', 'series', 'publisher', 'lang', 'isbn' ] unsorted_headers, rows = Mirror.get_headers_values(publications) # sort the headers by preferred order sorted_headers = [] for header in preferred_order: if header in unsorted_headers: sorted_headers.append(header) unsorted_headers.remove(header) # alphabetize the rest sorted_headers += sorted(unsorted_headers) term_c, term_r = os.get_terminal_size(0) table = BeautifulTable( default_alignment=BeautifulTable.ALIGN_LEFT, max_width=term_c - 1 ) table.column_headers = sorted_headers table.left_border_char = '' table.right_border_char = '' table.top_border_char = '━' table.bottom_border_char = ' ' table.header_separator_char = '━' table.row_separator_char = '─' table.intersection_char = '┼' table.column_separator_char = '│' # build a table using order of sorted_headers and blank out missing data for row in rows: expanded_row = [] for key in sorted_headers: if key in row.keys(): if type(row[key]) is list: expanded_row.append(','.join(row[key])) else: expanded_row.append(row[key]) else: expanded_row.append('') table.append_row(expanded_row) print(table) while True: try: choice = input('Choose publication by ID: ') publications = [p for p in publications if p.id == choice] if not publications: raise ValueError else: return publications[0] except ValueError: print('Invalid choice. Try again.') continue except (KeyboardInterrupt, EOFError) as e: print(e) sys.exit(1) break
z1 = initialization.spectral(k, G) Z1 = eclust.ztoZ(z1) # Hartigan's method zh = eclust.energy_hartigan(k, G, Z0) table[i,1] = accuracy(z, zh) zh = eclust.energy_hartigan(k, G, Z1) table[i,2] = accuracy(z, zh) # standard k-means km = KMeans(2) zh = km.fit_predict(Y) table[i, 3] = accuracy(z, zh) # GMM gmm = GMM(2) gmm.fit(Y) zh = gmm.predict(Y) table[i, 4] = accuracy(z, zh) t = BeautifulTable() t.column_headers = ["Method", "Mean Accuracy", "Std Error"] t.append_row(["Energy1D", table[:,0].mean(), sem(table[:,0])]) t.append_row(["H-Energy++:", table[:,1].mean(), sem(table[:,1])]) t.append_row(["H-Energy-top:", table[:,2].mean(), sem(table[:,2])]) t.append_row(["k-means:", table[:,3].mean(), sem(table[:,3])]) t.append_row(["GMM:", table[:,4].mean(), sem(table[:,4])]) print t
G = kernel_matrix(X, rho) # initialization mu0, z0 = initialization.kmeanspp(k, X, ret='both') Z0 = ztoZ(z0) z1 = initialization.spectral(k, G) Z1 = ztoZ(z1) t = BeautifulTable() t.column_headers = ["Method", "Accuracy", "Objective", "Exec Time"] start = timer() zh = energy_clustering_brute(k, G, Z0) end = timer() Zh = ztoZ(zh) t.append_row(["E-clustering brute", metric.accuracy(z, zh), objective(Zh, G), end-start]) start = timer() zh = energy_hartigan(k, G, Z0) end = timer() Zh = ztoZ(zh) t.append_row(["E-H-clustering++", metric.accuracy(z, zh), objective(Zh, G), end-start]) t.append_row(['Spectral Clustering:', metric.accuracy(z, z1), objective(Z1,G), '-']) start = timer() zh = energy_hartigan(k, G, Z1) end = timer() Zh = ztoZ(zh)