Пример #1
0
    def view(self, color=True, json=False):
        config = get_config_path()
        with open(config) as f:
            if json is True:
                config = preview_config(as_string=True)
                if color:
                    config = highlight(config, JsonLexer(), TerminalFormatter())
            else:
                config = f.read()
                if color:
                    config = highlight(config, IniLexer(), TerminalFormatter())

            print(config)
Пример #2
0
def nice_body(body, content=None, cssclass=None, encoding='utf-8'):
    if not body:
        return None
    cssclasses = ['codehilite']
    if cssclass:
        cssclasses.append(cssclass)
    classes = ' '.join(cssclasses)
    content = get_body_content_type(body, content)
    if content is not None:
        if 'x-www-form-urlencoded' in content:
            lex = IniLexer()
        elif 'json' in content:
            lex = JsonLexer()
        else:
            try:
                lex = get_lexer_for_mimetype(content, encoding=encoding)
            except ClassNotFound as e:
                return body

        if isinstance(lex, IniLexer):
            parsedbody = urlparse.parse_qsl(body, keep_blank_values=True)
            if body and not parsedbody:
                return tornado.escape.xhtml_escape(body)
            parsedbody = [(x.strip(), y) for [x, y] in parsedbody]
            args = collections.OrderedDict(sorted(parsedbody))
            params = "\n".join(
                [k.strip() + "=" + v for k, v in args.iteritems()])
            return highlight(
                params, IniLexer(),
                HtmlFormatter(cssclass=classes, encoding=encoding))
        elif isinstance(lex, JsonLexer):
            try:
                return highlight(json.dumps(json.loads(body), indent=4),
                                 JsonLexer(), HtmlFormatter(cssclass=classes))
            except ValueError as e:
                pass

    return highlight(body, lex,
                     HtmlFormatter(cssclass=classes, encoding=encoding))
Пример #3
0
    def print_file_contents(self, contents, file_name, raw):
        if raw or not self.user_io.out.is_terminal:
            self.user_io.out.writeln(contents)
            return

        from pygments import highlight
        from pygments.lexers import PythonLexer, IniLexer, TextLexer
        from pygments.formatters import TerminalFormatter

        if file_name.endswith(".py"):
            lexer = PythonLexer()
        elif file_name.endswith(".txt"):
            lexer = IniLexer()
        else:
            lexer = TextLexer()

        self.user_io.out.write(highlight(contents, lexer, TerminalFormatter()))
Пример #4
0
import os.path
import IPython

from pygments import highlight
from pygments.lexers import get_lexer_for_filename, TextLexer, IniLexer
from pygments.formatters import HtmlFormatter
from pygments.util import ClassNotFound

_custom_lexers = {'.config': IniLexer()}


def _custom_guess(path):
    _, ext = os.path.splitext(path)
    if ext in _custom_lexers:
        return _custom_lexers[ext]
    return TextLexer()


def prettyprint(path):
    try:
        lexer = get_lexer_for_filename(path)
    except ClassNotFound:
        lexer = _custom_guess(path)

    content = open(path).read()
    formatter = HtmlFormatter()
    return IPython.display.HTML('<style type="text/css">{}</style>{}'.format(
        formatter.get_style_defs('.highlight'),
        highlight(content, lexer, formatter)))

Пример #5
0
    def write_dossier(self):
        BMMuser, dcm, ga = user_ns['BMMuser'], user_ns['dcm'], user_ns['ga']
        if self.filename is None or self.start is None:
            print(error_msg('Filename and/or start number not given.'))
            return None
        firstfile = f'{self.filename}.{self.start:03d}'
        if not os.path.isfile(os.path.join(BMMuser.DATA, firstfile)):
            print(
                error_msg(
                    f'Could not find {os.path.join(BMMuser.DATA, firstfile)}'))
            return None

        # figure out various filenames
        basename = self.filename
        htmlfilename = os.path.join(BMMuser.DATA, 'dossier/',
                                    self.filename + '-01.html')
        seqnumber = 1
        if os.path.isfile(htmlfilename):
            seqnumber = 2
            while os.path.isfile(
                    os.path.join(BMMuser.DATA, 'dossier', "%s-%2.2d.html" %
                                 (self.filename, seqnumber))):
                seqnumber += 1
            basename = "%s-%2.2d" % (self.filename, seqnumber)
            htmlfilename = os.path.join(
                BMMuser.DATA, 'dossier',
                "%s-%2.2d.html" % (self.filename, seqnumber))

        ## generate triplot as a png image (or fail gracefully)
        prjfilename, pngfilename = None, None
        try:
            if self.uidlist is not None:
                pngfilename = os.path.join(BMMuser.DATA, 'snapshots',
                                           f"{basename}.png")
                #prjfilename = os.path.join(BMMuser.DATA, 'prj', f"{basename}.prj")
                self.make_merged_triplot(self.uidlist, pngfilename, self.mode)
        except Exception as e:
            print(error_msg('failure to make triplot'))
            print(e)

        # slurp in the INI file contents
        if self.initext is None:
            with open(os.path.join(BMMuser.DATA, self.inifile)) as f:
                self.initext = ''.join(f.readlines())

        # gather some information about the photon delivery system
        pdstext = f'{get_mode()} ({describe_mode()})'
        mono = 'Si(%s)' % dcm._crystal
        if self.ththth:
            mono = 'Si(333)'

        try:
            # dossier header
            with open(os.path.join(startup_dir, 'tmpl',
                                   'dossier_top.tmpl')) as f:
                content = f.readlines()
            thiscontent = ''.join(content).format(
                filename=self.filename,
                date=BMMuser.date,
                seqnumber=seqnumber,
            )

            # left sidebar, entry for XRF file in the case of fluorescence data
            thismode = plotting_mode(self.mode)
            if thismode == 'xs' or thismode == 'xs1':
                with open(
                        os.path.join(startup_dir, 'tmpl',
                                     'dossier_xrf_file.tmpl')) as f:
                    content = f.readlines()
                thiscontent += ''.join(content).format(
                    basename=basename,
                    xrffile=quote('../XRF/' + str(self.xrffile)),
                    xrfuid=self.xrfuid,
                )

            # middle part of dossier
            with open(os.path.join(startup_dir, 'tmpl',
                                   'dossier_middle.tmpl')) as f:
                content = f.readlines()
            thiscontent += ''.join(content).format(
                basename=basename,
                scanlist=self.scanlist,
                motors=self.motors,
                sample=self.sample,
                prep=self.prep,
                comment=self.comment,
                temperature=self.temperature,
                websnap=quote('../snapshots/' + self.websnap),
                webuid=self.webuid,
                anasnap=quote('../snapshots/' + self.anasnap),
                anauid=self.anauid,
                usb1snap=quote('../snapshots/' + self.usb1snap),
                usb1uid=self.usb1uid,
                usb2snap=quote('../snapshots/' + self.usb2snap),
                usb2uid=self.usb2uid,
            )

            # middle part, XRF and glancing angle alignment images
            if thismode == 'xs' or thismode == 'xs1':
                with open(
                        os.path.join(startup_dir, 'tmpl',
                                     'dossier_xrf_image.tmpl')) as f:
                    content = f.readlines()
                thiscontent += ''.join(content).format(
                    xrfsnap=quote('../XRF/' + str(self.xrfsnap)),
                    pccenergy='%.1f' % self.pccenergy,
                    ocrs=self.ocrs,
                    rois=self.rois,
                    symbol=self.element,
                )
                if 'glancing' in BMMuser.instrument:
                    with open(
                            os.path.join(startup_dir, 'tmpl',
                                         'dossier_ga.tmpl')) as f:
                        content = f.readlines()
                    thiscontent += ''.join(content).format(
                        ga_align=ga.alignment_filename,
                        ga_yuid=ga.y_uid,
                        ga_puid=ga.pitch_uid,
                        ga_fuid=ga.f_uid,
                    )

            # end of dossier
            with open(os.path.join(startup_dir, 'tmpl',
                                   'dossier_bottom.tmpl')) as f:
                content = f.readlines()
            thiscontent += ''.join(content).format(
                e0='%.1f' % self.e0,
                edge=self.edge,
                element=self.element_text(),
                mode=self.mode,
                bounds=self.bounds,
                steps=self.steps,
                times=self.times,
                seqstart=self.seqstart,
                seqend=self.seqend,
                mono=mono,
                pdsmode=pdstext,
                pccenergy='%.1f' % self.pccenergy,
                experimenters=self.experimenters,
                gup=BMMuser.gup,
                saf=BMMuser.saf,
                url=self.url,
                doi=self.doi,
                cif=self.cif,
                initext=highlight(self.initext, IniLexer(), HtmlFormatter()),
                clargs=highlight(self.clargs, PythonLexer(), HtmlFormatter()),
                filename=self.filename,
            )

            with open(htmlfilename, 'a') as o:
                o.write(thiscontent)

            print(f'wrote {htmlfilename}')
        except Exception as E:
            print(E)

        manifest = open(self.manifest_file, 'a')
        manifest.write(htmlfilename + '\n')
        manifest.close()
        self.write_manifest()

        if pngfilename is not None and os.path.isfile(pngfilename):
            try:
                img_to_slack(pngfilename)
            except:
                post_to_slack('failed to post image: {pngfilename}')
                pass

        return htmlfilename