예제 #1
0
def singleTry (buffer, options, arr_disp) :
    v = None
    x = XMLLoader(buffer, options, arr_disp)
    string_exception_caught = False
    string_exception_text = ""
    
    try :
        sys.stdout.write("READING XML:\n"+str(buffer)+"\n")
        sys.stdout.flush()
        v = x.expectXML()
        
        print "Converted to Tab:" 
        pretty.pretty(v)
        
        print "BACK TO XML:"
        sys.stdout.flush()
        os = StringIO.StringIO()
        xd = XMLDumper(os, XML_DUMP_PRETTY, array_disposition=arr_disp)
        xd.XMLDumpValue(v)
        print os.getvalue()
        
    except Exception,e :
        print e
        sys.stdout.flush()
        string_exception_caught = True;
        string_exception_text = str(e)
예제 #2
0
def singleTry(buffer, options, arr_disp):
    v = None
    x = XMLLoader(buffer, options, arr_disp)
    string_exception_caught = False
    string_exception_text = ""

    try:
        sys.stdout.write("READING XML:\n" + str(buffer) + "\n")
        sys.stdout.flush()
        v = x.expectXML()

        print "Converted to Tab:"
        pretty.pretty(v)

        print "BACK TO XML:"
        sys.stdout.flush()
        os = StringIO.StringIO()
        xd = XMLDumper(os, XML_DUMP_PRETTY, array_disposition=arr_disp)
        xd.XMLDumpValue(v)
        print os.getvalue()

    except Exception, e:
        print e
        sys.stdout.flush()
        string_exception_caught = True
        string_exception_text = str(e)
예제 #3
0
def runProgram(fileName):
    # process the prelude before running the program
    installPrelude()
    progStream = open(fileName)
    # now run the program
    exprList = _parseProg(progStream, processWhitespace=False, printExprs=False)
    result = evalStrict(*evalSequence(makeList(*exprList), topEnv))
    print pretty(result)
예제 #4
0
    def _sanity_check_merge_blavg_descriptors(self, merge_uvf, blavg_uvf):
        """
        Sanity check the merge UV file's metadata
        against that of the blavg UV file. Mostly we check that the
        frequency information is the same.
        """
        merge_desc = merge_uvf.Desc.Dict
        merge_fq_kw = dict(merge_uvf.tables["AIPS FQ"].keywords)
        merge_fq_rows = merge_uvf.tables["AIPS FQ"].rows

        blavg_desc = blavg_uvf.Desc.Dict
        blavg_fq_kw = dict(blavg_uvf.tables["AIPS FQ"].keywords)
        blavg_fq_rows = blavg_uvf.tables["AIPS FQ"].rows

        # Compare
        # (1) UV FITS descriptor
        # (2) FQ table keywords
        # (3) FQ table rows

        descriptor_keys = ('inaxes', 'cdelt', 'crval', 'naxis', 'crota', 'crpix',
                           'ilocu', 'ilocv', 'ilocw', 'ilocb', 'iloct', 'ilocsu',
                           'jlocc', 'jlocs', 'jlocf', 'jlocif', 'jlocr', 'jlocd')

        diff = {k: (merge_desc[k], blavg_desc[k]) for k in descriptor_keys
                if not merge_desc[k] == blavg_desc[k]}

        if len(diff) > 0:
            raise ValueError("merge and averaged UV descriptors differ "
                             "on the following keys:\n%s" % pretty(diff))

        diff = {k: (merge_fq_kw[k], blavg_fq_kw[k])
                for k in blavg_fq_kw.keys()
                if not merge_fq_kw[k] == blavg_fq_kw[k]}

        if len(diff) > 0:
            raise ValueError("merge and averaged FQ table keywords differ "
                             "on the following keys:\n%s" % pretty(diff))

        if not len(merge_fq_rows) == len(blavg_fq_rows):
            raise ValueError("merge (%d) and averaged (%d) FQ "
                             "number of rows differ"
                             % (len(merge_fq_rows), len(blavg_fq_rows)))

        diff = [("row %d" % r, {k: (mr[k], br[k]) for k in br.keys()
                if not mr[k] == br[k]})
                for r, (mr, br)
                in enumerate(zip(merge_fq_rows, blavg_fq_rows))]
        diff = [(r, d) for r, d in diff if len(d) > 0]

        if len(diff) > 0:
            raise ValueError("merge and averaged FQ rows "
                             "differ as follows\n:%s" % pretty(diff))
예제 #5
0
파일: views.py 프로젝트: tengentown/dollar
def subscribe(request):
    if request.method == 'POST':
        print(request.POST)
        #HOW DO WE RETURN json like: "{result:1}"
        new_subscriber = Subscriber(email=request.POST['email'])
        new_subscriber.save()
        return HttpResponse('{result:1, email:%s}' % request.POST['email'])

    if request.method == 'GET':
        email=request.GET['email']
           
        #AHHHH... I DONT KNOW DJANGO AT ALL :(
        pretty.pprint(request.environ)
        new_subscriber = Subscriber(email=email)
        new_subscriber.save()

        result = pretty.pretty(request.environ)
        data={ "result": result,
               "email": email
        }
        data_as_json = json.dumps(data)        

        resp = HttpResponse(data_as_json, "application/json")
        print dir(resp)
        return resp
예제 #6
0
파일: utils.py 프로젝트: connoryang/1v1dec
def pformat(obj, verbose = False):
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj)
예제 #7
0
def choose_assignment(session, course_id):
    course = 'https://camino.instructure.com/courses/' + course_id + '/gradebook'
    assignments = 'https://camino.instructure.com/api/v1/courses/' + course_id + '/assignment_groups'

    r = session.get(course)
    payload = {
        'include[]': 'assignments',
        'override_assignment_dates': 'false',
        'page_view_id': r.headers['x-request-context-id']
    }
    r = session.get(assignments, params=payload)
    dump = json.loads(r.content.split(';')[1])
    dump = dump[0]['assignments']

    links = []
    assignments = sorted(dump, key=itemgetter('id'))
    for index, assignment in enumerate(assignments):
        title = pretty(assignment['name'])
        url = assignment['html_url']
        links.append((title, url))
        print '\t%d: %s' % (index, title)
    i = int(stdin.readline().strip())
    if i >= len(links) and i < 0:
        print 'Selector outside range of list'
        sys.exit(1)
    print 'Assignment: %s' % links[i][0]
    # return the session (for cookies), name id, and url
    return (session, links[i][0], links[i][1])
예제 #8
0
def pformat(obj, verbose = False):
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj)
예제 #9
0
 def _requireObitImageMF(self):
     """Raise ValueError if this is not an ObitImageMF
     """
     if not self.isObitImageMF():
         raise ValueError("'%s' doesn't appear to be an ObitImageMF. "
                          "Descriptor is '%s'." %
                          (self.aips_path, pretty(self.Desc.Dict)))
예제 #10
0
def main(args):
    try:
        parser = etree.XMLParser(dtd_validation=True)
        root = etree.parse(args.xml, parser).getroot()
    except etree.XMLSyntaxError as e:
        error('syntax', repr(e))
        return 1

    protocol = Protocol.parse(root)

    if not validate(protocol):
        return 1

    if args.out:
        compile(protocol, args)

    if args.print:
        pretty(protocol)
예제 #11
0
def csvToXml(fname):
    with open(fname, "rb") as f:
        reder = csv.reader(f)
        header = reder.next()
        # print header
        root = Element("data")
        for row in reder:
            # print row
            # break
            erow = Element("row")
            root.append(erow)
            for tag, text in zip(header, row):
                e = Element(tag)
                e.text = text
                erow.append(e)
        pretty(root)
        et = ElementTree(root)
        et.write(fname + ".xml")
예제 #12
0
def pformat(obj, verbose=False):
    """Prettyprint an object.  Either use the `pretty` library or the
    builtin `pprint`.
    """
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj)
예제 #13
0
def pformat(obj, verbose=False):
    """Prettyprint an object.  Either use the `pretty` library or the
    builtin `pprint`.
    """
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj)
예제 #14
0
def mesg (expected, preamble,
	  instance, prototype, 
	  structure_match=True, type_match=EXACT_MATCH,
          thrw=False) :

    # strings for header
    sm = "NO"
    if structure_match : sm = "YES"
    
    if (type_match==EXACT_MATCH):
        conform = "EXACT_MATCH"
    elif (type_match==LOOSE_MATCH):
        conform= "LOOSE_MATCH"
    elif (type_match==LOOSE_STRING_MATCH):
        conform = "LOOSE_STRING_MATCH"
    else :
        raise Exception("Illegal conform?"+str(int(type_match)))
  
    # info about test
    print "---------", preamble, "\n----- structure_match:", sm, " type_match:", conform , " " , thrw 
    print "..............instance............"
    pretty(instance, sys.stdout)
    print
    print "..............prototype............." 
    pretty(prototype, sys.stdout)
    print
    
    # perform conforms
    result = False
    threw = False
    try :
        result = conforms(instance, prototype, structure_match, type_match, thrw)
        if result == None :
            print "!!!!!!!!!!!!!!!!!!!!!!! Should never return None !!!!!!!!!!!"
            sys.exit(1)
            
    except Exception, e :
        threw = True
        print "**MESSAGE CAUGHT:"
        print e
예제 #15
0
def fractional_bandwidth(uv_desc):
    """
    Returns the fractional bandwidth, given a uv descriptor dictionary

    Parameters
    ----------
    uv_desc : dict
        UV descriptor

    Returns
    -------
    float
        fractional bandwidth
    """
    try:
        ctypes = uv_desc['ctype']
    except KeyError:
        raise KeyError("The following UV descriptor is missing "
                       "a 'ctype': %s" % pretty(uv_desc))

    ctypes = [ct.strip() for ct in ctypes]

    try:
        freq_idx = ctypes.index('FREQ')
    except ValueError:
        raise ValueError("The following UV descriptor is missing "
                         "FREQ in it's 'ctype' field: %s" % pretty(uv_desc))

    freq_crval = uv_desc['crval'][freq_idx]
    freq_cdelt = uv_desc['cdelt'][freq_idx]
    freq_naxis = uv_desc['inaxes'][freq_idx]

    f1 = freq_crval
    f2 = freq_crval + freq_naxis * freq_cdelt

    return 2.0 * (f2 - f1) / (f2 + f1)
예제 #16
0
def interact(prompt="eval> "):
    prompt2 = ((len(prompt)-1)*'.')+' '
    buffer = []
    try:
        pmt = prompt
        while True:
            line = raw_input(pmt)
            pmt = prompt2
            buffer.append(line+'\n')
            if not line:
                val = null
                try:
                    for val in evalStream(StringIO("".join(buffer))):
                        pass
                    if val is not null:
                        print pretty(val)
                except Exception, e:
                    print "ERROR"
                    print e
                buffer = []
                pmt = prompt
    except EOFError:
        pass
    print
예제 #17
0
    def _select_and_infer_files(self):
        """
        Perform katdal selection and infer aips paths of:
        (1) imaging target names and indices
        (2) uv file for each target
        (3) clean file  for each target
        """

        self.katdal_select['reset'] = 'TFB'

        # Perform katdal selection
        self.ka.select(**self.katdal_select)

        # Fall over on empty selections
        if not self.ka.size > 0:
            raise ValueError("The katdal selection "
                             "produced an empty dataset"
                             "\n'%s'\n" % pretty(self.katdal_select))

        result_tuple = self._source_info()

        return result_tuple
예제 #18
0
    def _run_mfimage(self, uv_path, uv_sources):
        """
        Run the MFImage task
        """

        with uv_factory(aips_path=uv_path, mode="r") as uvf:
            merge_desc = uvf.Desc.Dict

        # Run MFImage task on merged file,
        out_kwargs = uv_path.task_output_kwargs(name='',
                                                aclass=IMG_CLASS,
                                                seq=0)
        out2_kwargs = uv_path.task_output2_kwargs(name='',
                                                  aclass=UV_CLASS,
                                                  seq=0)

        mfimage_kwargs = {}
        # Setup input file
        mfimage_kwargs.update(uv_path.task_input_kwargs())
        # Output file 1 (clean file)
        mfimage_kwargs.update(out_kwargs)
        # Output file 2 (uv file)
        mfimage_kwargs.update(out2_kwargs)
        mfimage_kwargs.update({
            'maxFBW': fractional_bandwidth(merge_desc)/20.0,
            'nThreads': multiprocessing.cpu_count(),
            'prtLv': self.prtlv,
            'Sources': uv_sources
        })

        # Finally, override with default parameters
        mfimage_kwargs.update(self.mfimage_params)

        log.info("MFImage arguments %s", pretty(mfimage_kwargs))

        mfimage = task_factory("MFImage", **mfimage_kwargs)
        # Send stdout from the task to the log
        with log_obit_err(log):
            mfimage.go()
예제 #19
0
def choose_assignment(session, course_id):
	course = 'https://camino.instructure.com/courses/' + course_id + '/gradebook'
	assignments = 'https://camino.instructure.com/api/v1/courses/' + course_id + '/assignment_groups'

	r = session.get(course)
	payload = {'include[]' : 'assignments', 'override_assignment_dates' : 'false' , 'page_view_id' : r.headers['x-request-context-id']}
	r = session.get(assignments, params = payload)
	dump = json.loads(r.content.split(';')[1])
	dump = dump[0]['assignments']
	
	links = []
	assignments = sorted(dump, key = itemgetter('id'))
	for index, assignment in enumerate(assignments):
		title = pretty(assignment['name'])
		url = assignment['html_url']
		links.append((title, url))
		print '\t%d: %s' %(index, title)
	i = int(stdin.readline().strip())
	if i >= len(links) and i < 0:
		print 'Selector outside range of list'
		sys.exit(1)
	print 'Assignment: %s' % links[i][0]
	# return the session (for cookies), name id, and url
	return (session, links[i][0], links[i][1])
예제 #20
0
supports_numeric = False
try:
    import Numeric
    supports_numeric = True
    array = Numeric.array
    types_map = pretty.NumericToOCMap
except:
    pass

supports_numpy = False
try:
    import numpy
    supports_numpy = True
    array = numpy.array
    types_map = pretty.NumPyToOCMap
except:
    pass

a = [1.123456789123456789, -100, 123456789]

for option_out in [pretty.LIKE_NUMERIC, pretty.LIKE_NUMPY, pretty.NATURAL]:
    pretty.ArrayOutputOption = option_out
    for typecode in types_map:
        print typecode

        b = array(a, typecode)
        print b
        pretty.pretty(b)
        print
예제 #21
0
파일: test.py 프로젝트: absop/Scheme
def pprint(code):
    print(pretty(code))
예제 #22
0
'''
Created on 17/07/2013

@author: drodri
'''
import pretty

if __name__ == '__main__':
    pretty.pretty()
예제 #23
0
def prettyPrint(x):
    print pretty.pretty(x)
    return null
예제 #24
0
def rename(dir):
    for f in os.listdir(dir):
        tmp = pretty(f)
        tmp = os.path.join(os.getcwd(), dir, tmp)
        f = os.path.join(os.getcwd(), dir, f)
        os.rename(f, tmp)
예제 #25
0
    p.pretty(obj.end)
    p.end_group(1, ')')


pretty._type_pprinters[ValueRange] = print_ValueRange

print("""# Generated
#  by {0}
#  from {1}
#  at {2}

from collections import OrderedDict
from .utils import ValueRange

COMMANDS = {commands}

ZONE_MAPPINGS = {zone_mappings}

COMMAND_MAPPINGS = {command_mappings}

VALUE_MAPPINGS = {value_mappings}
""".format(
    os.path.basename(sys.argv[0]),
    os.path.basename(sys.argv[1]),
    datetime.now(),
    commands=pretty.pretty(COMMANDS),
    zone_mappings=pretty.pretty(ZONE_MAPPINGS),
    command_mappings=pretty.pretty(COMMAND_MAPPINGS),
    value_mappings=pretty.pretty(VALUE_MAPPINGS),
))
예제 #26
0
    input_stdin = False
    output_stdout = False
    if (len(sys.argv) == 1):
        # use as filter: stdin and stdout
        input_stdin = True
        output_stdout = True
    elif (len(sys.argv) == 2):
        input_stdin = False
        output_stdout = True
    elif (len(sys.argv) != 3):
        print >> sys.stderr, "usage:", sys.argv[
            0], "[[input.xml] output.pythondictionary]"
        print >> sys.stderr, "         With no options, this reads stdin and output to stdout"
        sys.exit(1)

    xml_options = XML_STRICT_HDR | XML_LOAD_DROP_TOP_LEVEL | XML_LOAD_EVAL_CONTENT
    arr_disp = ARRAYDISPOSITION_AS_NUMPY  # ERIC_WRAPPER

    if arr_disp == ARRAYDISPOSITION_AS_NUMPY:
        from numpy import *
    if (input_stdin):
        v = ReadFromXMLStream(sys.stdin, xml_options, arr_disp)
    else:
        v = ReadFromXMLFile(sys.argv[1], xml_options, arr_disp)

    if (output_stdout):
        f = sys.stdout
    else:
        f = file(sys.argv[2], 'w')
    pretty(v, f)
예제 #27
0
파일: webapp.py 프로젝트: larsks/dropblog
 def dump(self):
     return pretty(self.config)
예제 #28
0
from pretty import pretty

try:
    from xml.etree.ElementTree import fromstring, tostring
except:
    from elementtree.ElementTree import fromstring, tostring



src = """<html:div xmlns:html="http://www.w3.org/1999/xhtml">
<html:p >I took a couple of days off work 
and we drove down to Florida to visit family in "The Villages", 
a 55+ golf cart community that currently has about 50,000 residents.
</html:p>
<html:p xmlns:html="http://www.w3.org/1999/xhtml">That is not a typo. Check out the <html:a href="http://en.wikipedia.org/wiki/The_Villages">wikipedia</html:a> <html:a href="http://en.wikipedia.org/wiki/The_Villages%2C_Florida">entries</html:a>.
</html:p>
<html:p xmlns:html="http://www.w3.org/1999/xhtml">On Monday we went out to feed the ducks at a nearby pond, but well fed
 by everyone else, they weren't interested in our bread. Instead the bread was 
 attacked from below by the fish in the pond, which wasn't very interesting, that is, until
 a local heron came over and started feasting on the fish we'd attracted. There's nothing
 like the sight of a still living fish wiggling down the throat of a heron to make
 a young boy's day.
</html:p>
<html:table style="width: 194px;" xmlns:html="http://www.w3.org/1999/xhtml"><html:tr><html:td align="center" style="height: 194px;"><html:a href="http://picasaweb.google.com/joe.gregorio/TheVillagesFlorida"><html:img height="160" src="http://lh6.google.com/joe.gregorio/RoK-XGNIkuE/AAAAAAAAAA8/ePqbYyHlxvU/s160-c/TheVillagesFlorida.jpg" style="margin: 1px 0 0 4px;" width="160" /></html:a></html:td></html:tr><html:tr><html:td style="text-align: center; font-family: arial,sans-serif; font-size: 11px;"><html:a href="http://picasaweb.google.com/joe.gregorio/TheVillagesFlorida" style="color: #4D4D4D; font-weight: bold; text-decoration: none;">The Villages, Florida</html:a></html:td></html:tr>
</html:table>
</html:div>"""


print pretty(fromstring(src))
예제 #29
0
from xmltools import *
import sys
from pretty import pretty
# Example showing how to read from an XML file and convert to Python dicts

if __name__=="__main__" :

    if len(sys.argv) !=2 : # read from filename provided
        print >> sys.stderr, sys.argv[0], " filename:  reads XML from a stream and converts to dicts"
        sys.exit(1)

    v = ReadFromXMLFile(sys.argv[1], \
                        XML_STRICT_HDR |          # want strict XML hdr
                        XML_LOAD_DROP_TOP_LEVEL | # XML _needs_ top-level
                        XML_LOAD_EVAL_CONTENT     # want real values,not strings
                        )
    pretty(v)
예제 #30
0
#!/usr/bin/env python

from sys import argv

from pretty import pretty
from evaluator import evaluate
from parser import parse
from sugar import desugar
from tokenizer import tokenize

if __name__ == '__main__':
  code = argv[1]

  print pretty(evaluate(desugar(parse(tokenize(code)))))
예제 #31
0
    sv = None
    stream_exception_caught = False
    stream_exception_text = ""

    ###os = buffer
    iss = StringIO.StringIO(buffer)
    xs = StreamXMLLoader(iss, options, arr_disp, XML_PREPEND_CHAR, True); # supress the warnings we normally generate so we don't see them twice in the output
    ###xs = XMLLoader(os, options, XML_PREPEND_CHAR, True); # supress the warnings we normally generate so we don't see them twice in the output
    try :
        sys.stdout.flush()
        sv = xs.expectXML()
    
        if (v != sv)  :
            # Stream version of output
            print "STREAM VERSION ERROR!!!!!!!!!!!!!!!!!!!!" 
            pretty.pretty(v)
            pretty.pretty(sv)
            sys.stdout.flush()
            print repr(v)==repr(sv)
            sys.exit(1)
            
    except Exception, e :
        # cout << e.what() << endl;
        stream_exception_caught = True
        stream_exception_text = str(e)
    
    # If exception
    if (string_exception_caught or stream_exception_caught) :
        if (stream_exception_caught==string_exception_caught) :
            if (stream_exception_text != string_exception_text) :
                print >> sys.stderr,  "ERROR: err messages for stream/string DO NOT match!"
try:
    import Numeric

    supports_numeric = True
    array = Numeric.array
    types_map = pretty.NumericToOCMap
except:
    pass

supports_numpy = False
try:
    import numpy

    supports_numpy = True
    array = numpy.array
    types_map = pretty.NumPyToOCMap
except:
    pass

a = [1.123456789123456789, -100, 123456789]

for option_out in [pretty.LIKE_NUMERIC, pretty.LIKE_NUMPY, pretty.NATURAL]:
    pretty.ArrayOutputOption = option_out
    for typecode in types_map:
        print typecode

        b = array(a, typecode)
        print b
        pretty.pretty(b)
        print
예제 #33
0
    stream_exception_caught = False
    stream_exception_text = ""

    ###os = buffer
    iss = StringIO.StringIO(buffer)
    xs = StreamXMLLoader(iss, options, arr_disp, XML_PREPEND_CHAR, True)
    # supress the warnings we normally generate so we don't see them twice in the output
    ###xs = XMLLoader(os, options, XML_PREPEND_CHAR, True); # supress the warnings we normally generate so we don't see them twice in the output
    try:
        sys.stdout.flush()
        sv = xs.expectXML()

        if (v != sv):
            # Stream version of output
            print "STREAM VERSION ERROR!!!!!!!!!!!!!!!!!!!!"
            pretty.pretty(v)
            pretty.pretty(sv)
            sys.stdout.flush()
            print repr(v) == repr(sv)
            sys.exit(1)

    except Exception, e:
        # cout << e.what() << endl;
        stream_exception_caught = True
        stream_exception_text = str(e)

    # If exception
    if (string_exception_caught or stream_exception_caught):
        if (stream_exception_caught == string_exception_caught):
            if (stream_exception_text != string_exception_text):
                print >> sys.stderr, "ERROR: err messages for stream/string DO NOT match!"
        p.pretty(obj[key])
        p.text(')')
    p.end_group(1, '])')
pretty._type_pprinters[OrderedDict] = print_ordereddict

print \
"""# Generated
#  by {0}
#  from {1}
#  at {2}

from collections import OrderedDict


COMMANDS = {commands}

ZONE_MAPPINGS = {zone_mappings}

COMMAND_MAPPINGS = {command_mappings}

VALUE_MAPPINGS = {value_mappings}
""".format(
    os.path.basename(sys.argv[0]), os.path.basename(sys.argv[1]), datetime.now(),
    commands=pretty.pretty(COMMANDS),
    zone_mappings=pretty.pretty(ZONE_MAPPINGS),
    command_mappings=pretty.pretty(COMMAND_MAPPINGS),
    value_mappings=pretty.pretty(VALUE_MAPPINGS),
)


예제 #35
0
    input_stdin = False
    output_stdout = False
    if (len(sys.argv)==1) :
        # use as filter: stdin and stdout
        input_stdin = True
        output_stdout = True
    elif (len(sys.argv)==2) :
        input_stdin = False
        output_stdout = True
    elif (len(sys.argv)!=3) :
        print >> sys.stderr, "usage:" , sys.argv[0] , "[[input.xml] output.pythondictionary]"
        print >> sys.stderr, "         With no options, this reads stdin and output to stdout" 
        sys.exit(1)

    xml_options = XML_STRICT_HDR | XML_LOAD_DROP_TOP_LEVEL | XML_LOAD_EVAL_CONTENT 
    arr_disp = ARRAYDISPOSITION_AS_NUMPY # ERIC_WRAPPER

    if arr_disp == ARRAYDISPOSITION_AS_NUMPY :
        from numpy import *
    if (input_stdin) :
        v = ReadFromXMLStream(sys.stdin, xml_options, arr_disp)
    else :
        v = ReadFromXMLFile(sys.argv[1], xml_options, arr_disp)

    if (output_stdout) :
        f = sys.stdout
    else :
        f = file(sys.argv[2], 'w')
    pretty(v, f)

예제 #36
0
파일: stubgen.py 프로젝트: zlqhem/stubgen
def pretty(doc, outstream=sys.stdout):
	contents = P.pretty(80, doc)
	outstream.write(contents)
예제 #37
0
def rename(dir):
	for f in os.listdir(dir):
		tmp = pretty(f)
		tmp = os.path.join(os.getcwd(), dir, tmp)
		f = os.path.join(os.getcwd(), dir, f)
		os.rename(f, tmp)
예제 #38
0
def process(inputStack, char, cursor):

    # Link shortcuts
    if char in SHORTCUTS:
        char = SHORTCUTS[char]

    # Update the input stack
    if char.isdigit():

        # Inputed a number
        if inputStack[cursor[0]] == '_':
            inputStack[cursor[0]] = ''
        if inputStack[cursor[0]].isdigit() or '.' in inputStack[
                cursor[0]] or not inputStack[cursor[0]]:
            inputStack[cursor[0]] += char
            cursor[1] += 1
        else:
            inputStack.insert(cursor[0] + 1, char)
            cursor[0] += 1
    elif char == '.':

        # Inputed a decimal point
        if inputStack[cursor[0]] == '_':
            inputStack[cursor[0]] = ''
        if inputStack[cursor[0]].isdigit():
            inputStack[cursor[0]] += char
            cursor[1] += 1
        elif not inputStack[cursor[0]]:
            inputStack[cursor[0]] = '0' + char
        else:
            inputStack.insert(cursor[0] + 1, '0' + char)
            cursor[0] += 1
    elif len(inputStack):

        # Clean up empty items
        cleaned = False
        i = len(inputStack)
        while i > 0:
            i -= 1
            if inputStack[i] in '_':
                if inputStack[i] == '_':

                    # Remove the corresponding operator
                    numLeft = 0
                    for j in range(i + 1, len(inputStack)):
                        if inputStack[j].isdigit() or '.' in inputStack[j]:
                            numLeft += 1
                        elif inputStack[j] in OPERATORS:
                            numLeft -= 1
                            if numLeft < 1:
                                del inputStack[j]
                                break
                if len(inputStack) > 1:
                    del inputStack[i]
                    if i <= cursor[0] and cursor[0] > 0:
                        cursor[0] -= 1
                    i -= 1
                    cleaned = True

        # See if an expression is nested
        numLeft = 0
        for i in range(cursor[0] + 1):
            if inputStack[i].isdigit() or '.' in inputStack[i]:
                numLeft += 1
            elif inputStack[i] in OPERATORS:
                numLeft -= 1
        nestedAfter = 0
        for i in range(len(inputStack)):
            if inputStack[i].isdigit() or '.' in inputStack[i]:
                nestedAfter += 1
            elif inputStack[i] in OPERATORS:
                nestedAfter -= 1
        if char in '\r ':

            # Inputed return (or space)
            inputStack.insert(cursor[0] + 1, '')
            cursor[0] += 1
        elif char in OPERATORS:

            # Inputed an operator
            if numLeft >= 2 and (nestedAfter >= 2
                                 or cursor[0] == len(inputStack) - 1):

                # Insert operator
                inputStack.insert(cursor[0] + 1, char)
                cursor[0] += 1
        elif char == '\x7f' and not cleaned:

            # Inputed a backspace
            if len(inputStack[cursor[0]]) == 1 and inputStack[
                    cursor[0]].isdigit():
                inputStack[cursor[0]] = '_'
            else:
                inputStack[cursor[0]] = inputStack[cursor[0]][:-1]
        elif char in 'rh' and not cleaned:

            # Inputed left
            if cursor[0] > 0:
                cursor[0] -= 1
        elif char in 'sl':

            # Inputde right
            if cursor[0] < len(inputStack) - 1:
                cursor[0] += 1

    # Clean up decimals
    clean = False
    while not clean:
        clean = True
        for i in range(len(inputStack)):
            if inputStack[i] not in '_' and i != cursor[0]:
                if inputStack[i][-1] == '.' or (inputStack[i][-1] == '0'
                                                and '.' in inputStack[i]):
                    inputStack[i] = inputStack[i][:-1]
                    clean = False
            elif len(inputStack[i]) > 1 and inputStack[i][
                    0] == '0' and '.' not in inputStack[i]:
                inputStack[i] = inputStack[i][1:]
                clean = False

    # Not used fully yet
    cursor[1] = len(inputStack[cursor[0]])

    clear()

    rows, columns = os.popen('stty size', 'r').read().split()
    goto(1, int(rows))

    # Print the input stack
    rpn = []
    counter = 1
    for i in range(len(inputStack) - 1, -1, -1):
        if inputStack[i].isdigit(
        ) or '.' in inputStack[i] or not inputStack[i]:
            counter -= 1
        elif inputStack[i] in OPERATORS:
            counter += 1
        rpn.insert(0, inputStack[i] if inputStack[i] else ' ')
        if i == cursor[0]:
            rpn[0] = '\x1b[7m' + rpn[0] + '\x1b[0m'
        if counter == 0:
            counter = 1
            if i > cursor[0]:
                rpn.clear()
            else:
                break
    write(' '.join(rpn))

    # Print separator
    writeAt(1, int(rows) - 1, '─' * int(columns))

    # Print the rendered stack
    exprs = getExprs(inputStack, cursor[0], OPERATORS, OPCLASSES)
    line = int(rows) - 1
    for exprTree in reversed(exprs):
        exprW, exprH, exprA, expr = pretty(exprTree)
        exprTree = exprTree.evaluated
        exprTree.nested = False
        evalW, evalH, evalA, eval = pretty(exprTree.evaluated)

        # Colour
        expr = [
            '\x1b[44m' + i.replace('\x1b[0m', '\x1b[0;44m') + '\x1b[0m'
            for i in expr
        ]
        eval = [
            '\x1b[42m' + i.replace('\x1b[0m', '\x1b[0;42m') + '\x1b[0m'
            for i in eval
        ]

        # Combine
        p = []
        maxH = max(exprH, evalH)
        maxA = max(exprA, evalA)

        maxDrop = max(exprH - exprA, evalH - evalA)
        newH = maxA + maxDrop

        while exprH < newH:
            if exprA < maxA:
                expr.insert(0, ' ' * exprW)
                exprA += 1
            else:
                expr.append(' ' * exprW)
            exprH += 1

        while evalH < newH:
            if evalA < maxA:
                eval.insert(0, ' ' * evalW)
                evalA += 1
            else:
                eval.append(' ' * evalW)
            evalH += 1

        for i in range(newH):
            p.append(expr[i] + ' ' * (int(columns) - exprW - evalW) + eval[i])

        # Display
        if line - maxH <= 0:
            break
        writeAt(1, line - exprH, '\n'.join(p))
        line -= maxH + 1
예제 #39
0
                             disk=args.disk,
                             aclass=args.aclass,
                             seq=args.seq,
                             dtype="AIPS")

    # Handle invalid sequence numbers
    if args.seq is None or args.seq < 1:
        aips_path.seq = next_seq_nr(aips_path)

    # Apply the katdal selection
    KA.select(**args.select)

    # Fall over on empty selections
    if not KA.size > 0:
        raise ValueError("The katdal selection produced an empty dataset"
                         "\n'%s'\n" % pretty(args.select))

    # UV file location variables
    with uv_factory(aips_path=aips_path,
                    mode="w",
                    nvispio=args.nvispio,
                    table_cmds=KA.default_table_cmds(),
                    desc=KA.uv_descriptor()) as uvf:

        # Write history
        uv_history_obs_description(KA, uvf)
        uv_history_selection(args.select, uvf)

        # Perform export to the file
        uv_export(KA, uvf)