我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用tabulate.tabulate()。
def default(self, line): "Execute a PostgreSQL statement" try: self.db.cursor.execute(line) except psycopg2.ProgrammingError, e: print e return try: data = self.db.cursor.fetchall() if data is not None: names = [row[0] for row in self.db.cursor.description] print tabulate.tabulate(data, headers=names) except psycopg2.ProgrammingError: # no results, eg from an insert/delete pass except TypeError, e: print e
def meraki_ap_fw_rules(status): json_fw_ap_list = meraki_requests("/networks/%s/ssids/%s/l3FirewallRules" % (args.network,args.ssid),meraki_api_key, "enable") global fw_ap_list key=0 for item in json_fw_ap_list: key +=1 # If there's only 2 firewall rules, then that's propably only the default meraki rules (which has their own string vars) if len(json_fw_ap_list) == 2: fw_ap_list.append([item["policy"],item["proto"],item["dst_cidr"],item["dst_port"],item["comment"]]) else: # Split by , (csv support) fw_ap_list_raw.append([item["policy"]+','+item["protocol"]+','+item["destCidr"]+','+item["destPort"]+','+item["comment"]]) fw_ap_list.append([item["policy"],item["protocol"],item["destCidr"],item["destPort"],item["comment"]]) print(tabulate(fw_ap_list,headers=['Policy','Protocol','Destination','Port','Comment'],tablefmt="rst")) if status == "pre": print("") print(tabulate(fw_ap_list_raw,headers=['- Copy paste output (use as template) -'],tablefmt="rst")) print("") return fw_ap_list # Import CSV file
def meraki_org_networks_ssid(network_id,network_name,org_id): url = "/networks/%s/ssids" % network_id json_data_networks_ssid = meraki_requests(url,meraki_api_key,"disable") global networks_list_ssid if json_data_networks_ssid: for item in json_data_networks_ssid: if item["enabled"] is True: item["enabled"] = "Enabled" if item["enabled"] is False: item["enabled"] = "Disabled" networks_list_ssid.append([network_id,network_name,org_id,item["name"],item["number"],item["enabled"]]) if meraki_debug == "1": print(tabulate(networks_list_ssid,headers=['Network ID','Network Name',"Organization ID","SSID","Number","Status"],tablefmt="rst")) return networks_list # Start script if running as standalone
def resources(cls, jobs_resources): jobs_resources = to_list(jobs_resources) click.clear() data = [['Job', 'Mem Usage/Limit', 'CPU%-CPUs', 'GPU Mem', 'GPU Usage']] for job_resources in jobs_resources: job_resources = ContainerResourcesConfig.from_dict(job_resources) line = [ job_resources.job_uuid.hex, '{} / {}'.format(job_resources.memory_used / (1024 ** 3), job_resources.memory_limit / (1024 ** 3)), '{} - {}'.format(job_resources.cpu_percentage, len(job_resources.percpu_percentage))] if job_resources.gpu_resources: pass data.append(line) click.echo(tabulate(data, headers="firstrow")) sys.stdout.flush()
def images(ctx, remote): """ List images """ utils.logger.debug("Executing images command") valid_images = ctx.obj.get('containers') or utils.get_images_from_dockerfiles() images_names = valid_images.keys() utils.logger.info("Expected images: %(images)s\n", dict(images=", ".join(images_names))) images_info = utils.get_local_images_info(images_names) if remote: _validate_global_params(ctx, 'registry') try: images_info += utils.get_remote_images_info(images_names, ctx.obj['registry']) except Exception as exp: raise click.exceptions.ClickException('Got unknow error from remote registry %(error)s' % dict(error=exp.message)) print(tabulate.tabulate(images_info, headers=['REGISTRY', 'IMAGE', 'TAG'], tablefmt='grid'))
def _code_pending(self, ctx, code): """Searches for a pending item by your confirmation code""" user = ctx.message.author settings = self.check_server_settings(user.server) headers = ["Time Stamp", "Name", "Item", "Confirmation#", "Status"] if user.id in settings["Pending"]: if code in settings["Pending"][user.id]: col1 = settings["Pending"][user.id][code]["Name"] col2 = settings["Pending"][user.id][code]["Time Stamp"] col3 = settings["Pending"][user.id][code]["Item"] col4 = settings["Pending"][user.id][code]["Confirmation Number"] col5 = settings["Pending"][user.id][code]["Status"] data = [(col2, col1, col3, col4, col5)] table = tabulate(data, headers=headers, numalign="left") msg = "```{}```".format(table) else: msg = "Could not find that code in your pending items." else: msg = "You have no pending items." await self.bot.say(msg)
def search_code(self, settings, code): userid = [subdict for subdict in settings["Pending"] if code in settings["Pending"][subdict]] if userid: userid = userid[0] col1 = settings["Pending"][userid][code]["Name"] col2 = settings["Pending"][userid][code]["Time Stamp"] col3 = settings["Pending"][userid][code]["Item"] col4 = settings["Pending"][userid][code]["Confirmation Number"] col5 = settings["Pending"][userid][code]["Status"] data = [(col1, col2, col3, col4, col5)] table = tabulate(data, headers=["Name", "Time Stamp", "Item", "Confirmation#", "Status"], numalign="left") msg = "```{}```".format(table) else: msg = "Could not find that confirmation number in the pending list." await self.bot.say(msg)
def check_user_pending(self, settings, user): try: if user.id in settings["Pending"]: column1 = [subdict["Name"] for subdict in settings["Pending"][user.id].values()] column2 = [subdict["Time Stamp"] for subdict in settings["Pending"][user.id].values()] column3 = [subdict["Item"] for subdict in settings["Pending"][user.id].values()] column4 = [subdict["Confirmation Number"] for subdict in settings["Pending"][user.id].values()] column5 = [subdict["Status"] for subdict in settings["Pending"][user.id].values()] data = list(zip(column2, column1, column3, column4, column5)) table = tabulate(data, headers=["Time Stamp", "Name", "Item", "Confirmation#", "Status"], numalign="left") msg = "```{}```".format(table) else: msg = "There are no pending items for this user." except AttributeError: msg = "You did not provide a valid user id." await self.bot.say(msg)
def _targets_heist(self, ctx): """Shows a list of targets""" server = ctx.message.server settings = self.check_server_settings(server) t_vault = settings["Theme"]["Vault"] if len(settings["Targets"].keys()) < 0: msg = ("There aren't any targets! To create a target use {}heist " "createtarget .".format(ctx.prefix)) else: target_names = [x for x in settings["Targets"]] crews = [int(subdict["Crew"]) for subdict in settings["Targets"].values()] success = [str(subdict["Success"]) + "%" for subdict in settings["Targets"].values()] vaults = [subdict["Vault"] for subdict in settings["Targets"].values()] data = list(zip(target_names, crews, vaults, success)) table_data = sorted(data, key=itemgetter(1), reverse=True) table = tabulate(table_data, headers=["Target", "Max Crew", t_vault, "Success Rate"]) msg = "```C\n{}```".format(table) await self.bot.say(msg)
def heist_game(self, settings, server, t_heist, t_crew, t_vault): crew = len(settings["Crew"]) target = self.heist_target(settings, crew) settings["Config"]["Heist Start"] = True players = [server.get_member(x) for x in settings["Crew"]] results = self.game_outcomes(settings, players, target) start_output = self.message_handler(settings, crew, players) await self.bot.say("Get ready! The {} is starting with {}\nThe {} has decided to " "hit **{}**.".format(t_heist, start_output, t_crew, target)) await asyncio.sleep(3) await self.show_results(settings, results) if settings["Crew"]: players = [server.get_member(x) for x in settings["Crew"]] data = self.calculate_credits(settings, players, target) headers = ["Players", "Credits Obtained", "Bonuses", "Total"] t = tabulate(data, headers=headers) msg = ("The credits collected from the {} was split among the winners:\n```" "C\n{}```".format(t_vault, t)) else: msg = "No one made it out safe." settings["Config"]["Alert Time"] = int(time.perf_counter()) self.reset_heist(settings) self.save_system() await self.bot.say(msg)
def _roll_dtable(self, dice: str, times=1, modifier=0): """Rolls a set of die in the format 2d12 By default only one set of die is rolled, without a modifier. Example 3d20 5 1 will roll three 1d20 dice for five seperate instances, with a +1 modifier added to the total.""" if times < 1: raise RollError("You need to have at least one roll instance.") elif times > 20: raise RollError("Cannot roll more than 20 instances at a time.") die, maximum = self.parse_dice(dice) rolls_raw = list(range(times)) if modifier < 0: sign = "" else: sign = "+" rolls = [(str("Roll {}".format(x + 1)), self.roll_dice(die, maximum), sign + str(modifier)) for x in rolls_raw] final = [x + (str(x[1] + modifier),) for x in rolls] headers = ["Roll", "Result", "Modifier", "Total"] t = tabulate(final, headers=headers) await self.bot.say("```{}```".format(t))
def roster(connect, model_name, since=None, until=None, count=None, verbose=False, **kwargs): mm = connect.lookup('model-manage') model = mm.models[model_name] snaps = model.snapshots.browse(since, until, count) if not verbose: for snap in snaps: print snap.id else: t = [ [x.id,model_name,x.created_on,x.stype,x.size] for x in snaps ] if len(t) > 0: print tabulate(t, headers=["Id","Model","Date/Time","Type","Size"]) else: print "No snapshots found"
def inspect(connect, slot=None, verbose=False, asjson=False, **kwargs): n = parse_slot(slot) engine = connect.lookup('engine') if slot == None: if asjson: doc = map(lambda x: x.to_dict(), engine.active_streams.values()) print json.dumps(doc, indent=2) else: t = [ [x.slot,x.name,transport(x.descriptor),str(x.eof)] for x in engine.active_streams.values() ] print tabulate(t, headers=["Slot","Name","Transport","EOF"]) elif n in engine.active_streams: info = engine.active_streams[n] if asjson: print json.dumps(info.to_dict(), indent=2) else: t = [[info.slot,info.name,transport(info.descriptor),str(info.eof)]] print tabulate(t, headers=["Slot","Name","Transport","EOF"]) else: if asjson: print "null" else: print "No stream attached to slot %s" % slot
def print_slot_map(slots): def stars(schema): if schema == None: return "-" s = json.dumps(schema) return s if len(s) <= 10 else "*****" def yesno(flag): return "Yes" if flag else "No" def glue(a, b): if len(a) > len(b): b += [[None] * 3] * (len(a) - len(b)) elif len(a) < len(b): a += [[None] * 4] * (len(b) - len(a)) return [ x + [None] + y for x,y in zip(a, b) ] left = [ [x.slot,stars(x.schema),x.action,yesno(x.recordsets)] for x in slots if x.slot % 2 == 0 ] right = [ [x.slot,stars(x.schema),yesno(x.recordsets)] for x in slots if x.slot % 2 == 1 ] headers = ["Slot","Schema","Action","Recordsets","","Slot","Schema","Recordsets"] print tabulate(glue(left, right), headers=headers)
def inspect(connect, tapid=None, verbose=False, asjson=False, **kwargs): if not connect.target: raise FastScoreError("Target not selected (see 'fastscore use')") sensors = connect.target.active_sensors if tapid != None: n = toint(tapid) if not n in sensors: raise FastScoreError("Sensor id %d not found" % n) if asjson: print json.dumps(sensors[n].to_dict(), indent=2) else: print "Sensor id %d is attached to '%s' at '%s'." \ % (n,sensors[n].tap,connect.target.name) elif asjson: print json.dumps(map(lambda x: x.to_dict(), sensors.values()), indent=2) else: if verbose: print "Sensors installed at '%s':" % connect.target.name t = [ [x.id,x.tap] for x in connect.target.active_sensors.values() ] print tabulate(t, headers = ["Id","Tap"])
def vfolders(args): ''' List and manage virtual folders. ''' fields = [ ('Name', 'name'), ('Created At', 'created_at'), ('Last Used', 'last_used'), ('Max Files', 'max_files'), ('Max Size', 'max_size'), ] if args.access_key is None: q = 'query { vfolders { $fields } }' else: q = 'query($ak:String) { vfolders(access_key:$ak) { $fields } }' q = q.replace('$fields', ' '.join(item[1] for item in fields)) try: resp = Admin.query(q) except BackendClientError as e: print_fail(str(e)) return print(tabulate((item.values() for item in resp['vfolders']), headers=(item[0] for item in fields)))
def agents(args): ''' List and manage agents. ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('First Contact', 'first_contact'), ('Mem.Slots', 'mem_slots'), ('CPU Slots', 'cpu_slots'), ('GPU Slots', 'gpu_slots'), ] try: items = Agent.list(args.status, fields=(item[1] for item in fields)) except BackendClientError as e: print_fail(str(e)) return if len(items) == 0: print('There are no matching agents.') return print(tabulate((item.values() for item in items), headers=(item[0] for item in fields)))
def process_nan_histogram(self, nphist, n_data): """Process nans histogram Add nans histogram to pdf list :param nphist: numpy-style input histogram, consisting of comma-separaged bin_entries, bin_edges :param int n_data: number of entries in the processed data set """ var_label = 'NaN count' x_label = 'Column name' y_label = self.hist_y_label if self.hist_y_label else None hist_file_name = 'hist_NaNs.pdf' pdf_file_name = '{0:s}/{1:s}'.format(self.results_path, hist_file_name) visualization.vis_utils.plot_histogram(nphist, x_label=x_label, y_label=y_label, is_num=False, is_ts=False, pdf_file_name=pdf_file_name) table = [('count', '{:d}'.format(n_data))] stats_table = tabulate.tabulate(table, tablefmt='latex') self.pages.append(self.page_template.replace('VAR_LABEL', var_label).replace('VAR_STATS_TABLE', stats_table) .replace('VAR_HISTOGRAM_PATH', hist_file_name))
def get_latex_table(self, get_stats=None, latex=True): """Get LaTeX code string for table of stats values :param list get_stats: List of statistics that you want to filter on. (default None (all stats)) Available stats are: 'count', 'filled', 'distinct', 'mean', 'std', 'min', 'max', 'p05', 'p16', 'p50', 'p84', 'p95', 'p99' :param bool latex: LaTeX output or list output (default True) :returns str: LaTeX code snippet """ # create statistics print lines if not self.stat_vals: self.create_stats() # create LaTeX string table = [(stat_var, self.stat_vals[stat_var][1]) for stat_var in self.stat_vars] if get_stats is not None: table = [(var, val) for var, val in table if var in get_stats] if latex: return tabulate.tabulate(table, tablefmt='latex') else: return table
def get_latex_table(self, get_stats=None): """Get LaTeX code string for group-by table of stats values :param list get_stats: same as ArrayStats.get_latex_table get_stats key word. :returns str: LaTeX code snippet """ # Explicitly strip the tables of their LaTeX headers and footers, concatenate the strings with a group-header # and reattach the LaTeX header and footer so that it parses to proper LaTeX. self.table = [] for group_key in sorted(self.stats_obj.keys()): s = self.stats_obj.get(group_key).get_latex_table(get_stats=get_stats, latex=False) self.table = self.table + [[group_key]] + s # The double list is needed for proper latex parsing if len(self.table) > 25: self.log().warning('The table is longer than 25 rows, the latex file will overflow.') return tabulate.tabulate(self.table, tablefmt='latex')
def main(options): if options.pretty_print and not HAS_TABULATE: print(Style.BRIGHT + Fore.RED + "Pretty printing requires tabulate python module. (pip install tabulate)") return init_api(options) cmd = options.commands switcher = { 'search': process_search, 'hunt': process_hunt, 'sign': process_sign, 'classify': process_classify, 'metadata': process_metadata, 'demo': process_demo } # Get the function from switcher dictionary process_fn = switcher.get(cmd) # Execute the function return process_fn(options)
def _dfw_rule_id_read_print(client_session, **kwargs): if not (kwargs['dfw_rule_name']): print ('Mandatory parameters missing: [-rname RULE NAME (use "" if name includes spaces)]') return None if not (kwargs['dfw_section_id']): print ('Mandatory parameters missing: [-sid SECTION ID]') return None dfw_section_id = str(kwargs['dfw_section_id']) dfw_rule_name = str(kwargs['dfw_rule_name']) dfw_rule_id = dfw_rule_id_read(client_session, dfw_section_id, dfw_rule_name) if kwargs['verbose']: print dfw_rule_id else: try: dfw_rule_ids_str = [str(ruleid) for ruleid in dfw_rule_id[dfw_rule_name]] dfw_rule_id_csv = ",".join(dfw_rule_ids_str) print tabulate([(dfw_rule_name, dfw_rule_id_csv)], headers=["Rule Name", "Rule IDs"], tablefmt="psql") except KeyError: print 'Rule name {} not found in section Id {}'.format(kwargs['dfw_rule_name'], kwargs['dfw_section_id'])
def _dfw_rule_list_print(client_session, **kwargs): l2_rule_list, l3_rule_list, l3r_rule_list = dfw_rule_list(client_session) if kwargs['verbose']: print l2_rule_list, l3_rule_list, l3r_rule_list else: print '' print '*** ETHERNET RULES ***' print tabulate(l2_rule_list, headers=["ID", "Name", "Source", "Destination", "Service", "Action", "Direction", "Packet Type", "Applied-To", "ID (Section)"], tablefmt="psql") print '' print '*** LAYER 3 RULES ***' print tabulate(l3_rule_list, headers=["ID", "Name", "Source", "Destination", "Service", "Action", "Direction", "Packet Type", "Applied-To", "ID (Section)"], tablefmt="psql") print'' print '*** REDIRECT RULES ***' print tabulate(l3r_rule_list, headers=["ID", "Name", "Source", "Destination", "Service", "Action", "Direction", "Packet Type", "Applied-To", "ID (Section)"], tablefmt="psql")
def _dfw_rule_destination_delete_print(client_session, **kwargs): if not (kwargs['dfw_rule_id']): print ('Mandatory parameters missing: [-rid RULE ID]') return None if not (kwargs['dfw_rule_destination']): print ('Mandatory parameters missing: [-dst RULE DESTINATION]') return None rule_id = kwargs['dfw_rule_id'] destination = kwargs['dfw_rule_destination'] rule = dfw_rule_destination_delete(client_session, rule_id, destination) if kwargs['verbose']: print rule else: print tabulate(rule, headers=["ID", "Name", "Source", "Destination", "Service", "Action", "Direction", "Packet Type", "Applied-To", "ID (Section)"], tablefmt="psql") #def dfw_rule_create(client_session, vccontent, section_id, rule_name, rule_direction, rule_pktype, rule_disabled, #rule_action, rule_applyto, rule_source_type, rule_source_name, rule_source_value, #rule_source_excluded, rule_destination_type, rule_destination_name, rule_destination_value, #rule_destination_excluded, rule_service_protocolname, rule_service_destport, #rule_service_srcport, rule_service_name, rule_note, rule_tag, rule_logged):
def _read(client_session, **kwargs): needed_params = ['esg_name'] if not check_for_parameters(needed_params, kwargs): return None result = read(client_session, kwargs['esg_name']) if result and kwargs['verbose']: print json.dumps(result) elif result: print tabulate([(result['dhcp']['enabled'], result['dhcp']['logging']['enable'], result['dhcp']['logging']['logLevel'])], headers=["DHCP Enabled", "Logging Enabled", "Log Level"], tablefmt="psql") else: print 'Failed to get DHCP status from Edge Services Gateway {}'.format(kwargs['esg_name'])
def top(): app.config.from_object('config.default') database.init_app(app) top_places = get_top_existing() headers = ['id', 'name', 'candidates', 'items', 'changesets'] places = [] for p, changeset_count in top_places: name = p.display_name if len(name) > 60: name = name[:56] + ' ...' places.append((p.place_id, name, p.candidate_count, p.item_count, changeset_count)) print(tabulate(places, headers=headers, tablefmt='simple'))
def print_results(file, out_file, file_type): names, results, dim = test_embeddings(file, file_type) table_data = [[name] + result for name, result in zip(names, results)] table = tabulate.tabulate(table_data, headers=['dataset', 'acc', 'prec', 'rec', 'f1'], tablefmt='simple', floatfmt='.3f') if out_file: with open(out_file, 'a') as f: f.write('\n') f.write('+++Joint+++\n') f.write(table) f.write('\n') else: print() print('+++Joint+++') print(table)
def print_results(file, out_file, file_type): names, results, std_devs, dim = test_embeddings(file, file_type) rr = [[u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(result, std_dev)] for result, std_dev in zip(results, std_devs)] table_data = [[name] + result for name, result in zip(names, rr)] table = tabulate.tabulate(table_data, headers=['dataset', 'acc', 'prec', 'rec', 'f1'], tablefmt='simple', floatfmt='.3f') if out_file: with open(out_file, 'a') as f: f.write('\n') f.write('+++CNN+++\n') f.write(table) f.write('\n') else: print() print('CNN') print(table)
def print_results(file, out_file, file_type): names, results, dim = test_embeddings(file, file_type) table_data = [[name] + result for name, result in zip(names, results)] table = tabulate.tabulate(table_data, headers=['dataset', 'acc', 'prec', 'rec', 'f1'], tablefmt='simple', floatfmt='.3f') if out_file: with open(out_file, 'a') as f: f.write('\n') f.write('+++Retrofit+++\n') f.write(table) f.write('\n') else: print() print('+++Retrofit+++') print(table)
def print_results(file, out_file, file_type): """ file: word embedding file out_file: if provided, where to write results file_type: word2vec, glove, tang, or bin """ names, results, dim = test_embeddings(file, file_type) table_data = [[name] + result for name, result in zip(names, results)] table = tabulate.tabulate(table_data, headers=['dataset', 'acc', 'prec', 'rec', 'f1'], tablefmt='simple', floatfmt='.3f') if out_file: with open(out_file, 'a') as f: f.write('\n') f.write('+++Average word vectors+++\n') f.write(table) f.write('\n') else: print() print('+++Average word vectors+++') print(table)
def print_results(out_file): names, results = test() table_data = [[name] + result for name, result in zip(names, results)] table = tabulate.tabulate(table_data, headers=['dataset', 'acc', 'prec', 'rec', 'f1'], tablefmt='simple', floatfmt='.3f') if out_file: with open(out_file, 'a') as f: f.write('\n') f.write('+++Bag-of-words+++\n') f.write(table) f.write('\n') else: print() print('+++Bag-of-words with L2 regularized Logistic Regression+++') print(table)
def get_assets(self): """Assets and asset pairs availalbe at the exchange Get all available assets and also traiding asset pairs from the exchange. """ table = [ ['ASSET', 'ALTNAME', 'DECIMALS'] ] for asset, props in self.kraken.get_assets().items(): table.append([asset, props['altname'], props['decimals']]) print(tabulate(table, headers="firstrow", numalign="right")) print("\n") table = [ ['PAIR', 'ALTNAME', 'DECIMALS'] ] for pair, props in self.kraken.get_asset_pairs().items(): table.append([pair, props['altname'], props['pair_decimals']]) print(tabulate(table, headers="firstrow", numalign="right"))
def clip_df(df, tablefmt='html'): """ Copy a dataframe as plain text to your clipboard. Probably only works on Mac. For format types see ``tabulate`` package documentation. :param pandas.DataFrame df: Input DataFrame. :param str tablefmt: What type of table? :return: None. """ if tablefmt == 'material': html = tabulate.tabulate(df, headers=df.columns, tablefmt='html') html = html.replace('<table>', '<table class="mdl-data-table mdl-js-data-table">') header = '<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">\n<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">\n<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>' html = header + '\n' + html else: html = tabulate.tabulate(df, headers=df.columns, tablefmt=tablefmt) pyperclip.copy(html) print('Copied {} table to clipboard!'.format(tablefmt)) return html
def lint(args): logger.process('Parsing Source Reference...') elems = Strings.parsing_elems(filename=args.file, encoding='utf8' if args.utf8 else None) logger.process('Check Duplicate Keys...') duplicates = [] for item, count in collections.Counter([e[0] for e in elems]).items(): if count > 1: duplicates.append((item, count)) if duplicates: table = [] table_file = [] logger.info('Find the following:') for key, count in duplicates: table.append([key, count]) for elem in elems: if elem[0] == key: table_file.append([elem[2], elem[0], elem[1]]) logger.info(tabulate(table, headers=['Key', 'Count'], showindex='always', tablefmt="orgtbl")) logger.debug('Detail:') logger.debug(tabulate(table_file, headers=['Line', 'Key', 'Value'], tablefmt="orgtbl")) logger.error('Duplicate Keys') exit(1) logger.success('lint success')
def parse_vt_filescans( apiresults ): VTRES = [] COLUMNS = [ 'Index', 'Source', 'ScanDate', 'Hash', 'Verdict' ] counter = 0 for scan in apiresults: for item in scan: counter += 1 if item['response_code'] == 0: VTRES.append([ counter, 'VirusTotal', '---', item['resource'].upper(), '---' ]) elif item['response_code'] == 1: VTRES.append([ counter, 'VirusTotal', item['scan_date'], item['resource'].upper(), '{}/{}'.format( item['positives'], item['total'] ) ]) TABLE = tabulate( VTRES, headers=COLUMNS ) return TABLE
def create_sddc(self): print('\n# Example: Create a SDDC ({}) in org {}:'. format(self.sddc_name, self.org_id)) provider = os.environ.get('VMC_PROVIDER', 'AWS') sddc_config = AwsSddcConfig( region='US_WEST_2', num_hosts=1, name=self.sddc_name, provider=provider) task = self.vmc_client.orgs.Sddcs.create(org=self.org_id, sddc_config=sddc_config) wait_for_task(task_client=self.vmc_client.orgs.Tasks, org_id=self.org_id, task_id=task.id, interval_sec=self.interval_sec) print('\n# Example: SDDC created:') self.sddc_id = task.resource_id sddc = self.vmc_client.orgs.Sddcs.get(self.org_id, self.sddc_id) print(tabulate([[sddc.id, sddc.name]], ["ID", "Name"]))
def delete_sddc(self): print('\n# Example: Delete SDDC {} from org {}'.format(self.sddc_id, self.org_id)) task = self.vmc_client.orgs.Sddcs.delete(org=self.org_id, sddc=self.sddc_id) wait_for_task(task_client=self.vmc_client.orgs.Tasks, org_id=self.org_id, task_id=task.id, interval_sec=self.interval_sec) print('\n# Example: Remaining SDDCs:'. format(self.org_id)) sddcs_list = self.vmc_client.orgs.Sddcs.list(self.org_id) headers = ["ID", "Name"] table = [] for sddc in sddcs_list: table.append([sddc.id, sddc.name]) print(tabulate(table, headers))
def print_in_style(catch,username) : table = [[1,username,catch[10:]]] headers = ["Sno.","Username", "Last Visit"] print tabulate(table, headers, tablefmt="fancy_grid") space() puts(colored.magenta("Note : press '1' to return back to menu.")) puts(colored.magenta("Note : press '0' to exit.")) space() x = int(raw_input("Action : ")) if(x == 1) : flag = 0 call_defined_function(menu(flag)) elif(x == 0) : clear() else : flag = 1 call_defined_function(menu(flag))
def donation_list(): # establish separate dictionary objects # results = collections.OrderedDict() donor_dict = {"Donors": []} totals_dict = {"Total $": []} # loop through donors data set and perform aggregate functions # for donor, donations in sorted(donors.items()): donor_dict["Donors"].append(donor) totals_dict["Total $"].append((sum(donations))) # combine dictionary objects into one for tabulate data input format # results.update(donor_dict) results.update(totals_dict) print(tabulate(results, headers="keys", tablefmt="fancy_grid", numalign="center")) # Add donor name to list #
def report_data(): # establish separate dictionary objects # results = collections.OrderedDict() donor_dict = {"Donors": []} totals_dict = {"Total $": []} num_results = {"Number of Donations": []} avg_results = {"Average Donation": []} # loop through donors data set and perform aggregate functions # for donor, donations in sorted(donors.items()): donor_dict["Donors"].append(donor) totals_dict["Total $"].append((sum(donations))) num_results["Number of Donations"].append(len(donations)) avg_results["Average Donation"].append(int(numpy.mean(donations))) # combine dictionary objects into one for tabulate data input format # results.update(donor_dict) results.update(totals_dict) results.update(num_results) results.update(avg_results) print(tabulate(results, headers="keys", tablefmt="fancy_grid", numalign="center")) user_input()
def __str__(self): from tabulate import tabulate rows = [] for name, stats in iteritems(self._stats): stats_dict = stats.dict del stats_dict['uvalues'] #stats_dict['hist'] = text_hist(stats_dict['hist'], True) if not rows: rows.append(list(stats_dict.keys())) rows.append(list(stats_dict.values())) if rows: table = tabulate(rows[1:], rows[0], tablefmt='pipe') return 'Statistics \n' + table else: return 'Statistics: None \n'
def print_table(table, row_names, col_names, latex_file = None): """Pretty prints the table given the table, and row and col names. If a latex_file is provided (and tabulate is installed), it also writes a file containing the LaTeX source of the table (which you can \input into your report) """ try: from tabulate import tabulate rows = map(lambda r,t: [r] + t, zip(row_names,table.tolist())) print(tabulate(rows, headers = [""] + col_names)) if latex_file is not None: latex_str = tabulate(rows, headers = [""] + col_names, tablefmt="latex") with open(latex_file, 'w') as f: f.write(latex_str) f.close() except ImportError as e: row_format ="{:>15} " * (len(col_names) + 1) print(row_format.format("", *col_names)) for row_name, row in zip(row_names, table): print(row_format.format(row_name, *row))
def desc_topic(client, args): """Print detailed information about a topic. :param client: KafkaClient connected to the cluster. :type client: :class:`pykafka.KafkaClient` :param topic: Name of the topic. :type topic: :class:`str` """ # Don't auto-create topics. if args.topic not in client.topics: raise ValueError('Topic {} does not exist.'.format(args.topic)) topic = client.topics[args.topic] print('Topic: {}'.format(topic.name)) print('Partitions: {}'.format(len(topic.partitions))) print('Replicas: {}'.format(len(topic.partitions.values()[0].replicas))) print(tabulate.tabulate( [(p.id, p.leader.id, [r.id for r in p.replicas], [r.id for r in p.isr]) for p in topic.partitions.values()], headers=['Partition', 'Leader', 'Replicas', 'ISR'], numalign='center', ))
def lookup(self, ctx, name=""): """Looks up a guild member by family name or character name""" try: members = Member.objects(Q(fam_name__icontains = name) | Q(char_name__icontains = name), server = ctx.message.server.id) rows = get_row(members, False) data = tabulate(rows, HEADERS, 'simple',) if members.count() == 1: await self.bot.say(codify(data) +"\n" + members.first().gear_pic) else: for page in paginate(data): await self.bot.say(page) except Exception as e: print(e) await self.bot.say("Something went horribly wrong")
def list(self,ctx,num=100): """List all the members and their gear score with optional limit. Example. gsbot list returns first 100 by default and gsbot list 5 first 5 sorted by gear score""" try: print('server,', ctx.message.server.id) members = Member.objects(server=ctx.message.server.id) print(Member.objects().first().server) rows = get_row(members, True, num) data = tabulate(rows, HEADERS, 'simple',) for page in paginate(data): await self.bot.say(page) except Exception as e: await self.bot.say("Something went horribly wrong") print(e)
def over(self, ctx, num=400): """List all the members over a certain gear score""" try: members = Member.objects(gear_score__gte = num, server = ctx.message.server.id) rows = get_row(members,False) data = tabulate(rows, HEADERS, 'simple',) for page in paginate(data): await self.bot.say(page) except Exception as e: print(e) await self.bot.say("Something went horribly wrong")
def delete(self, ctx, fam_name=''): """Deletes character from list. **officers can add an optional family name at the end to delete a certain user""" try: author = ctx.message.author if not fam_name: member = Member.objects(discord = author.id).first() else: member = Member.objects(fam_name = fam_name, server = ctx.message.server.id).first() roles = [u.name for u in author.roles] if ADMIN_USER not in roles: await self.bot.say("Only officers may perform this action") return info = [["Success Deleting User"], ["Character", member.char_name], ["Family", member.fam_name]] member.delete() await self.bot.say(codify(tabulate(info))) except Exception as e: print(e) await self.bot.say(codify("Error deleting user"))
def _status_table(bot: Bot, update: Update) -> None: """ Handler for /status table. Returns the current TradeThread status in table format :param bot: telegram bot :param update: message update :return: None """ # Fetch open trade trades = Trade.query.filter(Trade.is_open.is_(True)).all() if get_state() != State.RUNNING: send_msg('*Status:* `trader is not running`', bot=bot) elif not trades: send_msg('*Status:* `no active order`', bot=bot) else: trades_list = [] for trade in trades: # calculate profit and send message to user current_rate = exchange.get_ticker(trade.pair)['bid'] trades_list.append([ trade.id, trade.pair, shorten_date(arrow.get(trade.open_date).humanize(only_distance=True)), '{:.2f}'.format(100 * trade.calc_profit(current_rate)) ]) columns = ['ID', 'Pair', 'Since', 'Profit'] df_statuses = DataFrame.from_records(trades_list, columns=columns) df_statuses = df_statuses.set_index(columns[0]) message = tabulate(df_statuses, headers='keys', tablefmt='simple') message = "<pre>{}</pre>".format(message) send_msg(message, parse_mode=ParseMode.HTML)
def _count(bot: Bot, update: Update) -> None: """ Handler for /count. Returns the number of trades running :param bot: telegram bot :param update: message update :return: None """ if get_state() != State.RUNNING: send_msg('`trader is not running`', bot=bot) return trades = Trade.query.filter(Trade.is_open.is_(True)).all() message = tabulate({ 'current': [len(trades)], 'max': [_CONF['max_open_trades']] }, headers=['current', 'max'], tablefmt='simple') message = "<pre>{}</pre>".format(message) logger.debug(message) send_msg(message, parse_mode=ParseMode.HTML)