def print_first_point(filename): """ This function prints and returns the first data point (second row) from a csv file that includes a header row. """ #print city name for reference city = filename.split('-')[0].split('/')[-1] print('\nCity: {}'.format(city)) with open(filename, 'r') as f: ## TODO: Use the csv library to set up a DictReader object. ## ## see https://docs.python.org/3/library/csv.html ## trip_reader =csv.DictReader(f) ## TODO: Use a function on the DictReader object to read the ## ## first trip from the data file and store it in a variable. ## ## see https://docs.python.org/3/library/csv.html#reader-objects ## first_trip =trip_reader.__next__() ## TODO: Use the pprint library to print the first trip. ## ## see https://docs.python.org/3/library/pprint.html ## pp = pprint.PrettyPrinter() pp.pprint(first_trip) # output city name and first trip for later testing return (city, first_trip)
def get_ec2_price( self ): #, tenancy, operatingSystem, preInstalledSw, instanceType, location): response = PricingClient.get_instance().get_client().get_products( ServiceCode='AmazonEC2', Filters=[{ 'Type': 'TERM_MATCH', 'Field': 'operatingSystem', 'Value': 'Windows' }, { 'Type': 'TERM_MATCH', 'Field': 'vcpu', 'Value': '64' }, { 'Type': 'TERM_MATCH', 'Field': 'memory', 'Value': '256 GiB' }, { 'Type': 'TERM_MATCH', 'Field': 'preInstalledSw', 'Value': 'SQL Ent' }, { 'Type': 'TERM_MATCH', 'Field': 'location', 'Value': 'Asia Pacific (Mumbai)' }], MaxResults=100) for price in response['PriceList']: pp = pprint.PrettyPrinter(indent=1, width=300) pp.pprint(json.loads(price)) print()
def writeLimitsDict(folderextension, dataset, limitsDictOut): limitsDictFileName = folderextension + 'LimitsDict_' + dataset + '.py' print 'Writing signal limit info to', limitsDictFileName limitsDictFile = open(limitsDictFileName, 'w') import pprint pp = pprint.PrettyPrinter(indent=4, stream=limitsDictFile) pp.pprint(limitsDictOut) limitsDictFile.close()
def test_topic(self): t = GeektimesTopic(243447) pp = pprint.PrettyPrinter(indent=4) pp.pprint(t.author()) self.assertEqual(t.author(), 'SOUNDPAL') pp.pprint(t.title()) self.assertEqual(t.title(), 'На что влияет сопротивление наушников') pp.pprint(t.post['comments_count']) pp.pprint(t.post['rating'])
def test_topic(self): t = HabraTopic(231957) pp = pprint.PrettyPrinter(indent=4) pp.pprint(t.author()) self.assertEqual(t.author(), 'yaklamm') pp.pprint(t.title()) self.assertEqual(t.title(), 'Memory management в ядре Linux. Семинар в Яндексе') pp.pprint(t.post['comments_count']) pp.pprint(t.post['rating'])
def test_topic2(self): pp = pprint.PrettyPrinter(indent=4) pp.pprint("Start for post 208802") t = HabraTopic(208802) pp.pprint(t.author()) self.assertEqual(t.author(), 'icoz') self.assertEqual(t.title(), 'Экспорт Избранного на Хабре в PDF') pp.pprint(t.title()) pp.pprint(t.post['comments_count']) pp.pprint(t.post['rating']) # pp.pprint(t.comments()) # pp.pprint(t.comments()[1]) self.assertEqual(t.comments()[0]['author'], 'keccak') self.assertEqual(t.comments()[1]['author'], 'icoz')
def __str__(self): try: return self._api.__str__( self._data, self._request_kwargs, self._response, self._api_params ) except NotImplementedError: if type(self._data) == OrderedDict: return ("<{} object, printing as dict:\n" "{}>").format( self.__class__.__name__, json.dumps(self._data, indent=4) ) else: import pprint pp = pprint.PrettyPrinter(indent=4) return ("<{} object\n" "{}>").format( self.__class__.__name__, pp.pformat(self._data) )
def test_topic3(self): t = HabraTopic(28108) pp = pprint.PrettyPrinter(indent=4) pp.pprint(t.author()) self.assertEqual(t.author(), 'cachealot') self.assertEqual( t.title(), 'эффективное использование vim: «from the very begining»') pp.pprint(t.title()) pp.pprint(t.post['comments_count']) pp.pprint(t.post['rating']) self.assertEqual(t.comments()[0]['author'], 'cachealot') from lxml import html txt = html.fromstring(t.comments()[0]['text']).text_content().replace( "'", '').strip() self.assertEqual(txt, 'не поверите, 3,5 часа убил на пост )') self.assertEqual(t.comments()[0]['c_id'], 734629) self.assertEqual(t.comments()[0]['p_id'], 0) self.assertEqual(t.comments()[1]['author'], 'mirge') txt = html.fromstring(t.comments()[1]['text']).text_content().replace( "'", '').strip() self.assertEqual(txt, 'а 2 секунды на хабракат пожалели :)') self.assertEqual(t.comments()[1]['c_id'], 734630) self.assertEqual(t.comments()[1]['p_id'], 734629)
influx_port = os.getenv('INFLUX_PORT', '8086') influx_database = os.getenv('INFLUX_DATABASE', 'unifi') controller_uri = os.getenv('CONTROLLER_URI', 'https://unifi:8443') controller_username = os.getenv('CONTROLLER_USERNAME', 'admin') controller_password = os.getenv('CONTROLLER_PASSWORD', 'password') controller_verify = bool(strtobool(os.getenv('CONTROLLER_VERIFY', 'false'))) controller_site = os.getenv('CONTROLLER_SITE', 'default') default_tags = os.getenv('INFLUX_DEFAULTTAGS') client = InfluxDBClient(influx_host, influx_port) c = controller(endpoint=controller_uri, username=controller_username, password=controller_password, verify=controller_verify) s = c.sites[controller_site]() pp = pprint.PrettyPrinter(indent=4) try: default_tags = { 'hostname': s.sysinfo()[0]['hostname'], 'site': controller_site, 'desc': c.sites[controller_site]['desc'] } except: print("Could not generate site default tags") client.create_database(influx_database) client.switch_database(influx_database) current_data = {} last_app_dpi = 0
# ('age', 20) # ('name', 'kim') # addr: yongin # age: 20 # name: kim print('-' * 50) print('** pprint **') pprint.pprint(info) pprint.pprint(info, width=20) pprint.pprint(info, width=20, indent=4) # 출력 결과 # {'addr': 'yongin', 'age': 20, 'name': 'kim'} # {'addr': 'yongin', # 'age': 20, # 'name': 'kim'} # { 'addr': 'yongin', # 'age': 20, # 'name': 'kim'} print('** pprint.PrettyPrinter **') pp = pprint.PrettyPrinter(width=20, indent=4) pp.pprint(info) # 출력 결과 # { 'addr': 'yongin', # 'age': 20, # 'name': 'kim'}
def displayDataJson(jsondata): pp = pprint.PrettyPrinter(indent=4) pp.pprint(jsondata)
def lerstruct(p_path, out_dict, configobj, listaumelemento=True, maxlevel=-1, extractkey=None, extractvalues=None): stack = [] level = 0 tree = json.load(open(p_path)) keys_set = set([]) pp = pprint.PrettyPrinter(indent=4) # A stack é uma lista que contém os nós da árvore que foram 'tocados' # mas ainda não 'visitados'. Em cada nova 'visita' a um nó da árvore, # os nós que lhe são adjacentes são 'tocados' e colocados na stack para # serem 'visitados' em ciclos seguintes # No início, a stack contém apenas o nó raiz da árvore. stack.append([level, '--raiz--', tree, out_dict, []]) count = 0 while len(stack) > 0: # Retirar da stack um nó 'tocado'. currlevel, currid, currnode, outobj_node, tree_path_list = stack.pop() # if 'Eventos' in tree_path_list: # print(tree_path_list) # break # Chegámos ao final de um ramo da árvore if currnode is None: continue # Cada nova visita, a 'profundidade' aumenta newlevel = currlevel + 1 # Se tiver sido imposto um limite de 'profundidade' às visitas, # e esse limite tiver sido ultrapassado, vamos parar de 'tocar' # nós, impedindo novas colocações na stack if maxlevel >= 0 and newlevel > maxlevel: dostack = False else: dostack = True # Truncar prefixos de acordo com as configurações for prefx in configobj['prefixos_a_truncar']: currid = currid.replace(prefx, '') # Se o nó seguinte for um dicionário de uma só chave que contém # uma lista, vamos resumi-lo 'a lista nele contida if isinstance(currnode, dict) and len(currnode.keys()) == 1: keysl = list(currnode.keys()) singlekey = keysl[0] if isinstance(currnode[singlekey], list): currnode = currnode[singlekey] # if isinstance(currnode, dict): # keysl = list(currnode.keys()) # firstkey = keysl[0] # print(f"currid: {currid}, fkey:{firstkey}") # Se o nó seguinte for uma lista, riar e preencher uma lista # no objecto de saída if isinstance(currnode, list): # if len(currnode) == 1: # if isinstance(currnode[0], dict): # if len(currnode[0].keys()) == 1: # testobj = currnode[0][currnode[0].keys()[0]] # if isinstance(testobj, list) and len(testobj) > 1: # currnode = testobj try: currid = int(currid) except ValueError: pass try: if not isinstance(outobj_node, list): # outobj_node.append([]) # outobj_node = outobj_node[-1] # else: outobj_node[currid] = [] outobj_node = outobj_node[currid] except: print( f"currid: {currid} type: {type(currid)}, len:{len(outobj_node)}" ) pp.pprint(currnode) pp.pprint(outobj_node) raise if dostack: for ei, el in reversed(list(enumerate(currnode))): tree_path_list.append(ei) stack.append( [newlevel, str(ei), el, outobj_node, tree_path_list]) if listaumelemento: break elif isinstance(currnode, dict): oktogo = False if currid != '--raiz--' \ and not currid in configobj['atributos_a_ignorar']: okprefix_suffix = True for attrprf in configobj['prefixos_de_atributo_a_ignorar']: if currid.startswith(attrprf): okprefix_suffix = False break if okprefix_suffix: for attrsfx in configobj['sufixos_de_atributo_a_ignorar']: if currid.endswith(attrsfx): okprefix_suffix = False break if okprefix_suffix: oktogo = True if oktogo: if isinstance(outobj_node, list): outobj_node.append({}) outobj_node = outobj_node[-1] else: outobj_node[currid] = {} outobj_node = outobj_node[currid] if dostack: kl = list(currnode.keys()) kl.reverse() for key in kl: if len(kl) == 1 and isinstance(currnode[key], list): for ei, el in reversed(list(enumerate(currnode[key]))): tree_path_list.append(ei) stack.append([ newlevel, str(ei), el, outobj_node, tree_path_list ]) if listaumelemento: break else: tree_path_list.append(key) stack.append([ newlevel, key, currnode[key], outobj_node, tree_path_list ]) else: if extractkey == currid and not extractvalues is None: extractvalues.add(currnode) if not str(currid).strip().startswith('@'): if isinstance(outobj_node, list): outobj_node.append(currnode) elif isinstance(outobj_node, dict): outobj_node[currid] = currnode
import random import string import faker import requests from flask import render_template, redirect, url_for, flash, request, jsonify from flask_login import current_user, login_user, logout_user, login_required from werkzeug.urls import url_parse from app import app, db from app.custom import require_role from app.forms import LoginForm, RegistrationForm from app.models import User from pprint import pprint pprint = pprint.PrettyPrinter().pprint fake = faker.Faker() strgen = lambda length, charset=string.ascii_letters, weights=None: "".join( random.choices(list(charset), k=length, weights=weights)) @app.route("/", subdomain="api") def api_index(): return "api" @app.route("/time/") def time(): value = request.args.get("value") if not value: return "<br>".join([
def pprint(obj): import pprint pp = pprint.PrettyPrinter(indent=4) return pp.pprint(obj)
def showJSONData(jsondata): pp = pprint.PrettyPrinter(indent=4) pp.pprint(jsondata)
from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.model_selection import KFold from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedShuffleSplit import pandas as pd import numpy as np import operator import scikitplot as skplt import seaborn as sns; sns.set(style="ticks", color_codes=True) import pprint pretty = pprint.PrettyPrinter() ### Load the dictionary containing the dataset with open("final_project_dataset.pkl", "r") as data_file: data_dict = pickle.load(data_file) ### Convert the file to Pandas dataframe enron = pd.DataFrame.from_dict(data_dict, orient = 'index') print 'Example Value Dictionary of Features' pretty.pprint(data_dict['ALLEN PHILLIP K'])
def do_vm(self, args, arguments): """ :: Usage: vm create [VMNAME] [--count=VMNUMBER] [--debug] [--dryrun] vm start [VMNAME] [--vms=VMLIST] [--count=VMNUMBER] [--debug] [--dryrun] vm stop [--vms=VMLIST] [--debug] [--dryrun] vm destroy [--vms=VMLIST] [--debug] [--dryrun] vm status [--vms=VMLIST] [--dryrun] vm list vm resize [SIZE] vm rebuild [IMAGE] vm rename [NAME] vm publicip [--vms=VMLIST] vm ssh NAME vm run COMMAND [--vms=<vmList>] vm script run SCRIPT [--vms=<vmList>] [--dryrun] This command does some useful things. Arguments: FILE a file name Options: -f specify the file """ print(arguments) # noinspection PyShadowingNames def vm_manager(): config = Config() default_cloud = config.data["cloudmesh"]["default"]["cloud"] vm = Vm(default_cloud) return vm result = None if arguments.get("--debug"): pp = pprint.PrettyPrinter(indent=4) print("vm processing arguments") pp.pprint(arguments) # pp.pprint(config.data) if arguments.get("list"): vm = vm_manager() result = vm.nodes() elif arguments.get("start"): vm = vm_manager() try: result = vm.start(arguments.get("--vms")) except ValueError: vm_name = arguments.get("VMNAME") vm.create(vm_name) result = f"Created {vm_name}" elif arguments.get("stop"): vm = vm_manager() result = vm.stop(arguments.get("--vms")) elif arguments.get("destroy"): vm = vm_manager() result = vm.destroy(arguments.get("--vms")) elif arguments.get("status"): vm = vm_manager() result = vm.status(arguments.get("--vms")) elif arguments.get("publicip"): vm = vm_manager() result = vm.get_public_ips(arguments.get('--vms')) elif arguments.get("ssh"): vm = vm_manager() # TODO raise NotImplementedError( "cloud vm ssh command has not yet been implemented") elif arguments.get("run"): vm = vm_manager() # TODO raise NotImplementedError( "cloud vm run command has not yet been implemented") elif arguments.get("script"): vm = vm_manager() # TODO raise NotImplementedError( "cloud vm script command has not yet been implemented") return result
def str(self): return pprint.PrettyPrinter().pformat(self.session.report)