import sys from pprint import PrettyPrinter from django import forms from django.core.mail import send_mail from django.template import loader from core.company.models import Company dumper = PrettyPrinter(indent=4, stream=sys.stderr).pprint class SendEmailForm(forms.Form): name = forms.CharField(max_length='200', label='Nombre del restaurante') email = forms.EmailField(label='Email', ) def send_email(self): template = loader.get_template('restaurant/email.html') # url = 'http://localhost:9988/user/add' url = 'http://takeaway.jose-castro.com/user/add' html_message = template.render({'url': url}) send_mail('Registro', None, None, [self.cleaned_data['email']], fail_silently=False, html_message=html_message)
# The name of the DOCUMENTATION template EXAMPLE_YAML = os.path.abspath(os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, 'examples', 'DOCUMENTATION.yml' )) _ITALIC = re.compile(r"I\(([^)]+)\)") _BOLD = re.compile(r"B\(([^)]+)\)") _MODULE = re.compile(r"M\(([^)]+)\)") _URL = re.compile(r"U\(([^)]+)\)") _LINK = re.compile(r"L\(([^)]+),([^)]+)\)") _CONST = re.compile(r"C\(([^)]+)\)") _RULER = re.compile(r"HORIZONTALLINE") DEPRECATED = b" (D)" pp = PrettyPrinter() display = Display() # kludge_ns gives us a kludgey way to set variables inside of loops that need to be visible outside # the loop. We can get rid of this when we no longer need to build docs with less than Jinja-2.10 # http://jinja.pocoo.org/docs/2.10/templates/#assignments # With Jinja-2.10 we can use jinja2's namespace feature, restoring the namespace template portion # of: fa5c0282a4816c4dd48e80b983ffc1e14506a1f5 NS_MAP = {} def to_kludge_ns(key, value): NS_MAP[key] = value return ""
def main(indicator, indicator_type): full_details = otx.get_indicator_details_full(supported_types.get(indicator_type), indicator) pp = PrettyPrinter() pp.pprint(full_details)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from pprint import PrettyPrinter from typing import List custom_printer = PrettyPrinter( indent=4, width=100, depth=2, compact=True, sort_dicts=False, underscore_numbers=True, ) INPUT_FILE = "input.txt" LEFT_CHUNK_PAIRS = {"(": ")", "[": "]", "{": "}", "<": ">"} RIGHT_CHUNK_PAIRS = {")": "(", "]": "[", "}": "{", ">": "<"} SYNTAX_ERROR_SCORES = {")": 3, "]": 57, "}": 1197, ">": 25137} def read_chunks() -> List[List[str]]: chunks: List[List[str]] = [] with open(INPUT_FILE, "r", encoding="utf-8") as f_handle: for line in f_handle: line = line.rstrip() if line: chunks.append(list(line))
########## No configuration past this line ############### # Warming up out_fieldnames = ('Source', 'Category', 'Competitor', 'Manufacturer Part Number', 'Newark Part Number', 'Manufacturer', 'Description', 'Stock Value', 'Availability', 'Factory Lead Time', 'Quantity1', 'Price1', 'Quantity2', 'Price2', 'Quantity3', 'Price3', 'Quantity4', 'Price4', 'Quantity5', 'Price5', 'Quantity6', 'Price6', 'Quantity7', 'Price7', 'Quantity8', 'Price8', 'Quantity9', 'Price9', 'Quantity10', 'Price10', 'Currency', 'URL', 'Status', 'Status Message', 'CacheTime') ppr = PrettyPrinter(indent=2) class newark(retriever): baseurl = 'http://www.newark.com' def __init__(self): etree.set_default_parser(etree.HTMLParser()) super().__init__( pp, headers={ 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0', # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', # 'Accept-Encoding': 'gzip, deflate',
"""Compare two versions of a package. Parameters: pkg_name : str ver_1 : str ver_2 : str Returns: true if ver_1 is greater than ver_2 false if ver_1 is less than ver_2 Warnings: This function is right for the case that both versions do EXIST in releases """ releases = list(request_pkg_info(pkg_name)['releases'].keys()) if releases.index(ver_1) >= releases.index(ver_2): return True if releases.index(ver_1) <= releases.index(ver_2): return False if __name__ == '__main__': pkg_name = 'PySocks' conditions = [('<', '2.0'), ('!=', '1.5.7'), ('>=', '1.5.6')] PrettyPrinter(indent=2).pprint(get_possile_pkg_by(pkg_name, conditions)) print(pkg_ver_compare('PySocks', '1.5.7', '1.5.6')) print(pkg_ver_compare('PySocks', '1.5.6', '1.5.7'))
import tensorflow as tf import numpy as np import language_evaluation from tqdm import tqdm import colorful from sklearn.metrics import accuracy_score from data import vocabulary as data_vocab from data.wizard_of_wikipedia import (WowDatasetReader, PARLAI_KNOWLEDGE_SEPARATOR, BERT_KNOWLEDGE_SEPARATOR) from utils.etc_utils import check_none_gradients, check_nan_gradients from models import BaseModel from modules.from_parlai import normalize_answer pformat = PrettyPrinter().pformat class Trainer(object): def __init__(self, model: BaseModel, optimizer: tf.keras.optimizers.Optimizer = tf.keras. optimizers.Adam(), mirrored_strategy: tf.distribute.Strategy = None, enable_function: bool = True, preprocess_fn=lambda x: x): self.model = model self.optimizer = optimizer self.mirrored_strategy = mirrored_strategy self.enable_function = enable_function self.preprocess_fn = preprocess_fn
"""A small example of how to parse bin data and to access it afterhands.""" from pathlib import Path from future.utils import iteritems import pickle from pprint import PrettyPrinter from BinaryParser import SlidingParser from BinaryParser import GPRMC_extractor, temperatures_extractor, channel_stats_extractor import matplotlib.pyplot as plt pp = PrettyPrinter(indent=2).pprint # just a small helper function for displaying the available data def dump_keys(d, lvl=0): """Pretty print a dict showing only keys and size of the list entries.""" for k, v in iteritems(d): if type(v) == list: print("{}{}: size {}".format(lvl * ' ', k, len(v))) else: print("{}{}".format(lvl * ' ', k)) if type(v) == dict: dump_keys(v, lvl+1) # path to the data to parse # path_to_folder_data = Path("./all_example_data/example_data_geophone_temperature/")
def pp(*args, **kwargs): from pprint import PrettyPrinter pp = PrettyPrinter(indent=4).pprint pp(*args, **kwargs)
def show_list(): from pprint import PrettyPrinter PrettyPrinter(indent=4).pprint(VL)
def interleave(sep, iter): for started, value in enumerate(iter): if started: yield sep yield value # https://docs.python.org/3/library/itertools.html#itertools-recipes def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) PP = PrettyPrinter(indent=0, depth=1, width=80, compact=True) def short_str(x): text = PP.pformat(x) lines = text.splitlines(False) if len(lines) > 1: return lines[0][:20] + '...' + lines[-1][-20:] else: return text def format_metres(dist): if dist < 1000: return str(int(dist)) + M else:
def main(): """ Main function """ instance = ArgumentParser(description=__doc__) instance.add_argument("-j", "--jobNo", nargs="*", help="filter records by jobNo of jobs") instance.add_argument("-o", "--owner", nargs="*", help="filter records by owner of jobs") args = instance.parse_args() if (not args.jobNo) and (args.owner): for document in mongodb_conn(False).gisds.accountinglogs.find( {"jobs.owner": { "$in": args.owner }}): for job in document["jobs"]: if job["owner"] in args.owner: job["cpu"] = strftime("%Hh%Mm%Ss", gmtime(job["cpu"])) job["maxvmem"] = str(job["maxvmem"] / pow(2, 30)) + " GB" job["ruWallClock"] = strftime("%Hh%Mm%Ss", gmtime(job["ruWallClock"])) job["submissionTime"] = str( datetime.fromtimestamp( job["submissionTime"]).isoformat()).replace( ":", "-") PrettyPrinter(indent=2).pprint(job) if (args.jobNo) and (not args.owner): for document in mongodb_conn(False).gisds.accountinglogs.find( {"jobs.jobNo": { "$in": args.jobNo }}): for job in document["jobs"]: if job["jobNo"] in args.jobNo: job["cpu"] = strftime("%Hh%Mm%Ss", gmtime(job["cpu"])) job["maxvmem"] = str(job["maxvmem"] / pow(2, 30)) + " GB" job["ruWallClock"] = strftime("%Hh%Mm%Ss", gmtime(job["ruWallClock"])) job["submissionTime"] = str( datetime.fromtimestamp( job["submissionTime"]).isoformat()).replace( ":", "-") PrettyPrinter(indent=2).pprint(job) if args.jobNo and args.owner: for document in mongodb_conn(False).gisds.accountinglogs.find({ "jobs.jobNo": { "$in": args.jobNo }, "jobs.owner": { "$in": args.owner } }): for job in document["jobs"]: if (job["jobNo"] in args.jobNo) and (job["owner"] in args.owner): job["cpu"] = strftime("%Hh%Mm%Ss", gmtime(job["cpu"])) job["maxvmem"] = str(job["maxvmem"] / pow(2, 30)) + " GB" job["ruWallClock"] = strftime("%Hh%Mm%Ss", gmtime(job["ruWallClock"])) job["submissionTime"] = str( datetime.fromtimestamp( job["submissionTime"]).isoformat()).replace( ":", "-") PrettyPrinter(indent=2).pprint(job)
a = A(10) a2 = A(20) result = { u'a': a, u'a2': a2, u'a + a2': a + a2, u'a - a2': a - a2, u'cmp(a, a2)': cmp(a, a2) } pp = PrettyPrinter(indent=4, width=10) presult = pp.pformat(result) print u'result : \n{}'.format(presult) """ cnt = Counter(dict((x, A(y)) for x in xrange(5) for y in xrange(x + 5))) cnt2 = Counter(dict((x, A(y)) for x in xrange(-3, 2) for y in xrange(x + 5))) # for elem, value in cnt.items(): # print u'other["elem"] {0:>25}'.format(type(value)) # print type(cnt2) result = { u'cnt': cnt, u'cnt2': cnt2, u'cnt - cnt2': cnt - cnt2, u'cnt + cnt2': cnt + cnt2 } pp = PrettyPrinter(indent=4, width=80) print u'result = ' pp.pprint(result)
def __str__(self): p = PrettyPrinter(indent=2) return p.pformat(self.as_dict())
"""Entrypoint for challenge number 1""" import json from requests import put from pprint import PrettyPrinter from minisculus import MarkOne SUBMISSION_URL: str = "http://minisculuschallenge.com/14f7ca5f6ff1a5afb9032aa5e533ad95" pprint = PrettyPrinter().pprint def main(): mark_one: MarkOne = MarkOne(6) encoded_string: str = mark_one.encode("Strong NE Winds!") payload = {"answer": encoded_string} response = put(SUBMISSION_URL, data=json.dumps(payload).encode("UTF-8")) if response.status_code == 200: response_content = json.loads(response.content) pprint(response_content) else: pprint(response) if __name__ == "__main__": main()
import collections.abc from pprint import PrettyPrinter pprinter = PrettyPrinter() class Dict(dict): def __getattr__(self, key): try: return self[key] except KeyError: return object.__getattribute__(self, key) def __setattr__(self, key, value): self[key] = value @staticmethod def recursive(d: dict): root = Dict(d) for k, v in root.items(): if isinstance(v, dict) and (not isinstance(v, Dict)): root[k] = Dict.recursive(v) return root def __str__(self): return pprinter.pformat(self) def deep_update(d, u, _class=dict): for k, v in u.items(): if isinstance(v, collections.abc.Mapping):
import transaction import numpy as np from .models import (ImportedRecord, Oil, Estimated, Cut, SARAFraction, SARADensity, MolecularWeight) from .utilities.estimations import api_from_density from .imported_record.estimations import ImportedRecordWithEstimation from .imported_record.scoring import ImportedRecordWithScore from .oil.estimations import OilWithEstimation from pprint import PrettyPrinter pp = PrettyPrinter(indent=2, width=120) logger = logging.getLogger(__name__) class OilRejected(Exception): ''' Custom exception for Oil initialization that we can raise if we decide we need to reject an oil record for any reason. ''' def __init__(self, message, oil_name, *args): # without this you may get DeprecationWarning self.message = message # Special attribute you desire with your Error, # perhaps the value that caused the error?:
import datetime import time import os import re import copy from functools import cmp_to_key from pprint import PrettyPrinter import toml from builder.dashboard import Dashboard from builder.docker import DockerRegistry, DockerHelper from subprocess import PIPE, Popen pprint = PrettyPrinter(1).pprint EMSCRIPTEN_REPO = "https://github.com/emscripten-core/emscripten/" DOCKER_REGISTRY = "registry.hub.docker.com" # TODO: remove DOCKER_REPO = "trzeci/emscripten" QUEUE_FILE = "queue.txt" LOG_COMPILATION = "build.log" ROOT = os.path.realpath( os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) config = toml.load(open("config.toml", "r"))
def test_builtin_prettyprinter(): # non regression test than ensures we can still use the builtin # PrettyPrinter class for estimators (as done e.g. by joblib). # Used to be a bug PrettyPrinter().pprint(LogisticRegression())
from historia.country import Country, Province from historia.pops import Pop, make_initial_pops, PopType from historia.economy import make_RGOs, RGOType, Good from historia.map import WorldMap from historia.world import give_hex_natural_resources from historia.log import HistoryLogger from historia.enums import HexType, DictEnum from historia.utils import ChangeStore, Change, Timer from termcolor import colored default_params = {'start_date': arrow.get(1, 1, 1), 'run_months': 1} from pprint import PrettyPrinter pp = PrettyPrinter(indent=4, depth=6) echo = pp.pprint class JsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Change): return obj.export() if isinstance(obj, DictEnum): return obj.ref() return json.JSONEncoder.default(self, obj) class Historia(object): """ Keeps track of everything in history, and the current time in history
def main(): from pprint import PrettyPrinter printer = PrettyPrinter(indent=4) printer.pprint(config)
from pprint import PrettyPrinter pp = PrettyPrinter(indent=2) pp2 = pp pp4 = PrettyPrinter(indent=4) class BadSteamGameInfoException(Exception): def __init__(self,bad_info={},msg=''): self.bad_info=bad_info self.msg=msg class steam_game(): def __init__(self,steam_game_info, owner_personaname='Unknown Game Owner', owner_steamid=-1): self.steam_game_info=steam_game_info img_url_template='http://media.steampowered.com/steamcommunity/public/images/apps/{0}/{1}.jpg' if 'appid' in steam_game_info.keys(): self.appid = steam_game_info['appid'] if 'appid' in steam_game_info.keys() else -1 if 'img_icon_url' in steam_game_info.keys(): self.img_icon_url = img_url_template.format(self.appid,steam_game_info['img_icon_url']) elif 'empty_steam_game_img_icon_url' in steam_game_info.keys(): self.img_icon_url = 'https://steamcommunity-a.akamaihd.net/public/shared/images/header/globalheader_logo.png' else: raise BadSteamGameInfoException(steam_game_info,'self.img_icon_url failure') if 'img_logo_url' in steam_game_info.keys(): self.img_logo_url = img_url_template.format(self.appid,steam_game_info['img_logo_url']) elif 'empty_steam_game_img_logo_url' in steam_game_info.keys(): self.img_logo_url = 'https://steamcommunity-a.akamaihd.net/public/shared/images/header/globalheader_logo.png' else: raise BadSteamGameInfoException(steam_game_info,'self.img_logo_url failure') else: raise BadSteamGameInfoException(steam_game_info,'appid failure')
A module that contains the model classes for forklift ''' import logging from inspect import getsourcefile from os.path import dirname, join from pprint import PrettyPrinter from time import clock import arcpy from xxhash import xxh64 from . import config, seat from .messaging import send_email pprinter = PrettyPrinter(indent=4, width=40) names_cache = {} class Pallet(object): '''A module that contains the base class that should be inherited from when building new pallet classes. Pallets are plugins for the forklift main process. They define a list of crates and any post processing that needs to happen. In order for a pallet to be recognized by forklift, the file within which it is defined needs to have `pallet` (case-insensitive) somewhere in the filename. Multiple pallets with the same filename will cause issues so it's strongly recommended to keep them unique. Appending the project name to the file name is the convention.''' def __init__(self, arg=None):
hd, tl, ",".join( sorted(rts, key=lambda e: int(e))), idx) return out, fmt def menu_tree(self, node, out): for i in self.menu_main(node)["children"]: out.append(i) self.menu_tree(i, out) return out if __name__ == "__main__": from pprint import PrettyPrinter, pprint m = MenuItems() print "#" * 20 menues = [] m.menu_tree([], menues) PrettyPrinter(indent=1).pprint(menues) print "#" * 30 leafs = [i for i in menues if not m.menu_main(i)["children"]] print "#" * 30 shows = list(m.menu_shows(m.menu_main(leafs[30])["url"])) PrettyPrinter(indent=1).pprint(shows) print "#" * 30 PrettyPrinter(indent=1).pprint(m.menu_play(shows[2]["url"])) else: SCRAPER = MenuItems()
def main(parser) : args = parser.parse_args( ) if args.version : print( "MotionWise_Log.py v%s" % (__version__, ) ) sys.exit(0) try : # extract SWC_Pp<>_De<> from argument SWC_Pp_De = args.PpDe.split('.')[0] except : # notify user aout the invalid argument print( 'invalid argument "%s"'%(args.PpDe or "")) print( 'you must specify a valid RTE-Message that you want to receive' ) sys.exit(0) # explicit ra-initialization - we start the rx-thread later by hand ra = RA( parser, args,init=False ) # determine required routing and callback identifiers ra_cb_element_id = ra.get_element_id( "RA_%s"%SWC_Pp_De ) if ( ra_cb_element_id is None ) : print ( 'element id for "%s" not found' % SWC_Pp_De ) return port_routing_id = ra.get_port_id_of_port_name( SWC_Pp_De.split('_De')[0] ) if ( port_routing_id is None ) : print ( 'port routing id for "%s" not found' % SWC_Pp_De ) return #little helper to allow immediate shutdown on single-sot mode global_sh_lock = thread.allocate_lock() global_sh_lock.acquire() # compose callback function argument set ftp_callback_arguments = \ { 'pretty_print' : PrettyPrinter(indent=4).pprint , 'De_path' : '.'.join(args.PpDe.split('.')[1:]) , 'lock' : global_sh_lock } # create reference to wrapped callback function ref_cba_ccp = functools.partial \ ( callback_dex_complex , **ftp_callback_arguments ) # tell the callback function to unregister itsef once executed if args.single_shot : ref_cba_ccp.keywords['f_stop_receive'] = ra.receiving_stop # now initialize ra.init() # dont flood the net - turn off transmission of trace message # ra.config_trace(0,False) # register callback function ra.callback_add( ra_cb_element_id, ref_cba_ccp) # apply routing configuration if not forbidden by cmd-line if not args.no_auto_route : ra.config_routing_port( port_routing_id, 'record' ) ra.config_routing_sync( ) # start receive thread ra.receiving_start() # little looping so polite try : print( "press ctrl-c to stop" ) while( global_sh_lock.locked() ) : time.sleep( 0.5 ) except KeyboardInterrupt as e: # stop receive thread ra.receiving_stop() # apply routing configuration if not forbidden by cmd-line if not args.no_auto_route : ra.config_routing_port( port_routing_id, 'default' ) ra.config_routing_sync( ) # the clean way ra.shutdown()
def main(): pp = PrettyPrinter(indent=2) yelp = Yelp() details = yelp.get_business() pp.pprint(details)
else: # if it's a GET request context = { # TODO: Add context variable here for the full list of filter types 'filter_type_names': filter_types, } return render_template('image_filter.html', **context) ################################################################################ # GIF SEARCH ROUTE ################################################################################ api_key = os.getenv('API_KEY') TENOR_URL = 'https://api.tenor.com/v1/search' pp = PrettyPrinter(indent=4) @app.route('/gif_search', methods=['GET', 'POST']) def gif_search(): """Show a form to search for GIFs and show resulting GIFs from Tenor API.""" if request.method == 'POST': # TODO: Get the search query & number of GIFs requested by the user, store each as a # variable users_gif = request.form.get('search_query') gif_quantity = request.form.get('quantity') response = requests.get( TENOR_URL, { # TODO: Add in key-value pairs for:
def prettyPrint(self, x): """Print any object with %.3f precision and nice format.""" PrettyPrinter().pprint(pformat(x, formatfloat))
# # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import inspect, os import numpy as np import pickle import json import sys from optparse import OptionParser from tabulate import tabulate import itertools import matplotlib.pyplot as plt from pprint import PrettyPrinter pprint = PrettyPrinter(indent=4).pprint from htmresearch.support.lateral_pooler.datasets import load_data from htmresearch.support.lateral_pooler.utils import random_id, add_noise from htmresearch.support.lateral_pooler.metrics import mean_mutual_info_from_model, reconstruction_error # from htmresearch.frameworks.sp_paper.sp_metrics import reconstructionError from nupic.algorithms.spatial_pooler import SpatialPooler as SpatialPooler from sp_wrapper import SpatialPoolerWrapper from htmresearch.algorithms.lateral_pooler import LateralPooler from htmresearch.support.lateral_pooler.callbacks import (ModelCheckpoint, ModelOutputEvaluator, Reconstructor, ModelInspector, OutputCollector, Logger)
def pprint(thing): PrettyPrinter(indent=4).pprint(thing)