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
python类tabulate()的实例源码
cisco_meraki_fw_ap_rules_api.py 文件源码
项目:cisco-meraki-fw-ap-rules-api
作者: robertcsapo
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
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
cisco_meraki_fw_ap_rules_api.py 文件源码
项目:cisco-meraki-fw-ap-rules-api
作者: robertcsapo
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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)