Create the HTML for the FastQC adapter plot
502613
def adapter_content_plot (self):
        

        data = dict()
        for s_name in self.fastqc_data:
            try:
                for d in self.fastqc_data[s_name]['adapter_content']:
                    pos = self.avg_bp_from_range(d['position'])
                    for r in self.fastqc_data[s_name]['adapter_content']:
                        pos = self.avg_bp_from_range(r['position'])
                        for a in r.keys():
                            k = "{} - {}".format(s_name, a)
                            if a != 'position':
                                try:
                                    data[k][pos] = r[a]
                                except KeyError:
                                    data[k] = {pos: r[a]}
            except KeyError:
                pass
        if len(data) == 0:
            log.debug('adapter_content not found in FastQC reports')
            return None

        # Lots of these datasets will be all zeros.
        # Only take datasets with > 0.1% adapter contamination
        data = {k:d for k,d in data.items() if max(data[k].values()) >= 0.1 }

        pconfig = {
            'id': 'fastqc_adapter_content_plot',
            'title': 'FastQC: Adapter Content',
            'ylab': '% of Sequences',
            'xlab': 'Position (bp)',
            'yCeiling': 100,
            'yMinRange': 5,
            'ymin': 0,
            'xDecimals': False,
            'tt_label': '<b>Base {point.x}</b>: {point.y:.2f}%',
            'hide_empty': True,
            'yPlotBands': [
                {'from': 20, 'to': 100, 'color': '#e6c3c3'},
                {'from': 5, 'to': 20, 'color': '#e6dcc3'},
                {'from': 0, 'to': 5, 'color': '#c3e6c3'},
            ],
        }

        if len(data) > 0:
            plot_html = linegraph.plot(data, pconfig)
        else:
            plot_html = '<div class="alert alert-info">No samples found with any adapter contamination > 0.1%</div>'

        # Note - colours are messy as we've added adapter names here. Not
        # possible to break down pass / warn / fail for each adapter, which
        # could lead to misleading labelling (fails on adapter types with
        # little or no contamination)

        self.add_section (
            name = 'Adapter Content',
            anchor = 'fastqc_adapter_content',
            description = '''The cumulative percentage count of the proportion of your
            library which has seen each of the adapter sequences at each position.''',
            helptext = '''
            Note that only samples with &ge; 0.1% adapter contamination are shown.

            There may be several lines per sample, as one is shown for each adapter
            detected in the file.

            From the [FastQC Help](http://www.bioinformatics.babraham.ac.uk/projects/fastqc/Help/3%20Analysis%20Modules/10%20Adapter%20Content.html):

            _The plot shows a cumulative percentage count of the proportion
            of your library which has seen each of the adapter sequences at each position.
            Once a sequence has been seen in a read it is counted as being present
            right through to the end of the read so the percentages you see will only
            increase as the read length goes on._
            ''',
            plot = plot_html
        )
1036502
def highcharts_heatmap (data, xcats, ycats, pconfig=None):
    
    if pconfig is None:
        pconfig = {}

    # Reformat the data for highcharts
    pdata = []
    for i, arr in enumerate(data):
        for j, val in enumerate(arr):
            pdata.append([j,i,val])

    # Get the plot ID
    if pconfig.get('id') is None:
        pconfig['id'] = 'mqc_hcplot_'+''.join(random.sample(letters, 10))

    # Sanitise plot ID and check for duplicates
    pconfig['id'] = report.save_htmlid(pconfig['id'])

    # Build the HTML for the page
    html = '<div class="mqc_hcplot_plotgroup">'

    # The 'sort by highlights button'
    html += """<div class="btn-group hc_switch_group">
        <button type="button" class="mqc_heatmap_sortHighlight btn btn-default btn-sm" data-target="#{id}" disabled="disabled">
            <span class="glyphicon glyphicon-sort-by-attributes-alt"></span> Sort by highlight
        </button>
    </div>""".format(id=pconfig['id'])

    # The plot div
    html += '<div class="hc-plot-wrapper"><div id="{id}" class="hc-plot not_rendered hc-heatmap"><small>loading..</small></div></div></div> \n'.format(id=pconfig['id'])

    report.num_hc_plots += 1

    report.plot_data[pconfig['id']] = {
        'plot_type': 'heatmap',
        'data': pdata,
        'xcats': xcats,
        'ycats': ycats,
        'config': pconfig
    }

    return html
158706
def html(self, report, f):
        
        env = Environment(loader=PackageLoader('clan', 'templates'))

        template = env.get_template('report.html')

        context = {
            'report': report,
            'GLOBAL_ARGUMENTS': GLOBAL_ARGUMENTS,
            'field_definitions': self.field_definitions,
            'format_comma': format_comma,
            'format_duration': format_duration,
            'format_percent': format_percent
        }

        f.write(template.render(**context).encode('utf-8'))
424612
def main():
    mesh = parse_gmsh('../commands.msh', '../boundary_lines.dat')

    # now create the CRTomo grid
    

    str_header = get_header(mesh)
    str_nodes = get_nodes(mesh)
    str_elements = get_elements(mesh)
    str_adj_boundaries, boundary_elements = get_ajd_bound(mesh)

    crt_mesh = str_header + str_nodes + str_elements + str_adj_boundaries

    fid = open('../elem.dat', 'w')
    fid.write(crt_mesh)
    fid.close()

    write_elec_file('../electrode_positions.dat', mesh)
    debug_plot_mesh(mesh, boundary_elements)
1151961
def create_tdplot(plotman, cov, mag, pha, pha_fpi, alpha, options):
    '''
    '''
    sizex, sizez = getfigsize(plotman)
    # create figure
    f, ax = plt.subplots(2, 4, figsize=(4 * sizex, 2 * sizez))
    if options.title is not None:
        plt.suptitle(options.title, fontsize=18)
    # plot magnitue
    if options.cmaglin:
        cid = plotman.parman.add_data(np.power(10, mag))
        loglin = 'rho'
    else:
        cid = plotman.parman.add_data(mag)
        loglin = 'log_rho'
    plot_mag(cid, ax[0, 0], plotman, 'Magnitude', loglin, alpha,
             options.mag_vmin, options.mag_vmax,
             options.xmin, options.xmax, options.zmin, options.zmax,
             options.unit, options.mag_cbtiks, options.no_elecs,
             )
    # plot coverage
    cid = plotman.parman.add_data(cov)
    plot_cov(cid, ax[1, 0], plotman, 'Coverage',
             options.cov_vmin, options.cov_vmax,
             options.xmin, options.xmax, options.zmin, options.zmax,
             options.unit, options.cov_cbtiks, options.no_elecs,
             )
    # plot phase, real, imag
    create_non_dcplots(plotman, ax, mag, pha, options, alpha)
    # plot fpi phase, real, imag
    create_fpiplots(plotman, ax, mag, pha_fpi, options, alpha)
    f.tight_layout()
    f.savefig('td_overview.png', dpi=300)
    return f, ax
831176
def export_html(path="./plot.html", to_png=false)
      path = File.expand_path(path, Dir::pwd)
      body = generate_html("../templates/iruby.erb")
      temp_path = File.expand_path("../templates/static_html.erb", __FILE__)
      template = File.read(temp_path)
      num = File.write(path, ERB.new(template).result(binding))
      "Plot was saved to " + path
    end
871946
def render(self, fname=''):
        
        import qnet.visualization.circuit_pyx as circuit_visualization
        from tempfile import gettempdir
        from time import time, sleep

        if not fname:

            tmp_dir = gettempdir()
            fname = os.path.join(tmp_dir, "tmp_{}.png".format(hash(time)))

        if circuit_visualization.draw_circuit(self, fname):
            done = False
            for k in range(20):
                if os.path.exists(fname):

                    done = True
                    break
                else:
                    sleep(.5)
            if done:
                return fname

        raise CannotVisualize()
797031
def render(self, **kwargs):
        """"""
        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        header = self._template.module.__dict__.get('header', None)
        if header is not None:
            figure.header.add_child(Element(header(self, kwargs)),
                                    name=self.get_name())

        html = self._template.module.__dict__.get('html', None)
        if html is not None:
            figure.html.add_child(Element(html(self, kwargs)),
                                  name=self.get_name())

        script = self._template.module.__dict__.get('script', None)
        if script is not None:
            figure.script.add_child(Element(script(self, kwargs)),
                                    name=self.get_name())

        for name, element in self._children.items():
            element.render(**kwargs)
343885
def render(self, **kwargs):
        
        # Calling parent function
        super(VisSurface, self).render(**kwargs)

        # Initialize a list to store VTK actors
        vtk_actors = []

        # Start plotting
        for plot in self._plots:
            # Plot control points
            if plot['type'] == 'ctrlpts' and self.vconf.display_ctrlpts:
                vertices = [v.data for v in plot['ptsarr'][0]]
                faces = [q.data for q in plot['ptsarr'][1]]
                # Points as spheres
                pts = np.array(vertices, dtype=np.float)
                vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                actor1 = vtkh.create_actor_pts(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                               name=plot['name'], index=plot['idx'])
                vtk_actors.append(actor1)
                # Quad mesh
                lines = np.array(faces, dtype=np.int)
                actor2 = vtkh.create_actor_mesh(pts=vtkpts, lines=lines, color=vtkh.create_color(plot['color']),
                                                name=plot['name'], index=plot['idx'], size=self.vconf.line_width)
                vtk_actors.append(actor2)

            # Plot evaluated points
            if plot['type'] == 'evalpts' and self.vconf.display_evalpts:
                vertices = [v.data for v in plot['ptsarr'][0]]
                vtkpts = numpy_to_vtk(vertices, deep=False, array_type=VTK_FLOAT)
                vtkpts.SetName(plot['name'])
                faces = [t.data for t in plot['ptsarr'][1]]
                tris = np.array(faces, dtype=np.int)
                actor1 = vtkh.create_actor_tri(pts=vtkpts, tris=tris, color=vtkh.create_color(plot['color']),
                                               name=plot['name'], index=plot['idx'])
                vtk_actors.append(actor1)

            # Plot trim curves
            if self.vconf.display_trims:
                if plot['type'] == 'trimcurve':
                    pts = np.array(plot['ptsarr'], dtype=np.float)
                    vtkpts = numpy_to_vtk(pts, deep=False, array_type=VTK_FLOAT)
                    vtkpts.SetName(plot['name'])
                    actor1 = vtkh.create_actor_polygon(pts=vtkpts, color=vtkh.create_color(plot['color']),
                                                       name=plot['name'], index=plot['idx'], size=self.vconf.trim_size)
                    vtk_actors.append(actor1)

        # Render actors
        return vtkh.create_render_window(vtk_actors, dict(KeyPressEvent=(self.vconf.keypress_callback, 1.0)),
                                         figure_size=self.vconf.figure_size)
1323628
public void render( QrCode qr ) {
		initialize(qr);

		render.init();
		positionPattern(0,0, qr.ppCorner);
		positionPattern((numModules-7)*moduleWidth,0, qr.ppRight);
		positionPattern(0,(numModules-7)*moduleWidth, qr.ppDown);

		timingPattern(7*moduleWidth,6*moduleWidth,moduleWidth,0);
		timingPattern(6*moduleWidth,7*moduleWidth,0,moduleWidth);

		formatInformation();

		if( qr.version >= QrCode.VERSION_ENCODED_AT)
			versionInformation();

		// render alignment patterns

		int alignment[] = QrCode.VERSION_INFO[qr.version].alignment;
		for (int i = 0; i < alignment.length; i++) {
			int row = alignment[i];

			for (int j = 0; j < alignment.length; j++) {
				if( i == 0 & j == 0 )
					continue;
				if( i == alignment.length-1 & j == 0)
					continue;
				if( i == 0 & j == alignment.length-1)
					continue;

				int col = alignment[j];
				alignmentPattern(col,row);
			}
		}

		if( renderData ) {

			if( qr.rawbits.length != QrCode.VERSION_INFO[qr.version].codewords )
				throw new RuntimeException("Unexpected length of raw data.");

			// mark which modules can store data
			bitLocations = new QrCodeCodeWordLocations(qr.version).bits;

			int numBytes = bitLocations.size() / 8;
			if (numBytes != qr.rawbits.length)
				throw new RuntimeException("Egads. unexpected length of qrcode raw data");

			// Render the output data
			renderData();
		}

		qr.bounds.set(0,0,0);
		qr.bounds.set(1,markerWidth,0);
		qr.bounds.set(2,markerWidth,markerWidth);
		qr.bounds.set(3,0,markerWidth);
	}
636384
def make_report(plots, settings):
    '''
    
    '''
    logging.info("Writing html report.")
    html_content = ['<body>']

    # Hyperlink Table of Contents panel
    html_content.append('<div class="panel panelC">')
    if settings["filtered"]:
        html_content.append(
            '<p><strong><a href="#stats0">Summary Statistics prior to filtering</a></strong></p>')
        html_content.append(
            '<p><strong><a href="#stats1">Summary Statistics after filtering</a></strong></p>')
    else:
        html_content.append(
            '<p><strong><a href="#stats0">Summary Statistics</a></strong></p>')
    html_content.append('<p><strong><a href="#plots">Plots</a></strong></p>')
    html_content.extend(['<p style="margin-left:20px"><a href="#' +
                         p.title.replace(' ', '_') + '">' + p.title + '</a></p>' for p in plots])
    html_content.append('</div>')

    # The report itself: stats
    html_content.append('<div class="panel panelM"> <h1>NanoPlot report</h1>')
    if settings["filtered"]:
        html_content.append('<h2 id="stats0">Summary statistics prior to filtering</h2>')
        html_content.append(utils.stats2html(settings["statsfile"][0]))
        html_content.append('<h2 id="stats1">Summary statistics after filtering</h2>')
        html_content.append(utils.stats2html(settings["statsfile"][1]))
    else:
        html_content.append('<h2 id="stats0">Summary statistics</h2>')
        html_content.append(utils.stats2html(settings["statsfile"][0]))

    # The report itself: plots
    html_content.append('<h2 id="plots">Plots</h2>')
    for plot in plots:
        html_content.append('\n<h3 id="' + plot.title.replace(' ', '_') + '">' +
                            plot.title + '</h3>\n' + plot.encode())
        html_content.append('\n<br>\n<br>\n<br>\n<br>')
    html_body = '\n'.join(html_content) + '</div></body></html>'
    html_str = utils.html_head + html_body
    htmlreport = settings["path"] + "NanoPlot-report.html"
    with open(htmlreport, "w") as html_file:
        html_file.write(html_str)
    return htmlreport
156004
def generate_html(temp_path)
      path = File.expand_path(temp_path, __FILE__)
      url = Nyaplot.get_url
      id = SecureRandom.uuid
      model = to_json
      template = File.read(path)
      ERB.new(template).result(binding)
    end
893617
def _htmlRenderDict(pathParts, statDict, output):
  """"""
  keys = list(statDict.keys())
  keys.sort()

  links = []

  output.write('<div class="level">')
  for key in keys:
    keyStr = cgi.escape(_utf8str(key))
    value = statDict[key]
    if hasattr(value, '__call__'):
      value = value()
    if hasattr(value, 'keys'):
      valuePath = pathParts + (keyStr,)
      if isinstance(value, scales.StatContainer) and value.isCollapsed():
        link = '/status/' + '/'.join(valuePath)
        links.append('<div class="key"><a href="%s">%s</a></div>' % (link, keyStr))
      else:
        output.write('<div class="key">%s</div>' % keyStr)
        _htmlRenderDict(valuePath, value, output)
    else:
      output.write('<div><span class="key">%s</span> <span class="%s">%s</span></div>' %
                   (keyStr, type(value).__name__, cgi.escape(_utf8str(value)).replace('\n', '<br/>')))

  if links:
    for link in links:
      output.write(link)

  output.write('</div>')
1130878
def plot(self, data, w=800, h=420):
        """"""
        return HTML(
            self.iframe.format(
                source=self.render(
                    data=data, div_id="chart", head=self.head),
                w=w,
                h=h))
1306845
def _fastfood_show(args):
    """"""
    template_pack = pack.TemplatePack(args.template_pack)
    if args.stencil_set:
        stencil_set = template_pack.load_stencil_set(args.stencil_set)
        print("Stencil Set %s:" % args.stencil_set)
        print('  Stencils:')
        for stencil in stencil_set.stencils:
            print("    %s" % stencil)
        print('  Options:')
        for opt, vals in stencil_set.manifest['options'].items():
            print("    %s - %s" % (opt, vals['help']))
762457
def _figure_data(self, plot, fmt='html', doc=None, as_script=False, **kwargs):
        
        model = plot.state
        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        for m in model.references():
            m._document = None

        doc.theme = self.theme
        doc.add_root(model)

        # Bokeh raises warnings about duplicate tools and empty subplots
        # but at the holoviews level these are not issues
        logger = logging.getLogger(bokeh.core.validation.check.__file__)
        logger.disabled = True

        if fmt == 'png':
            from bokeh.io.export import get_screenshot_as_png
            img = get_screenshot_as_png(plot.state, None)
            imgByteArr = BytesIO()
            img.save(imgByteArr, format='PNG')
            data = imgByteArr.getvalue()
            if as_script:
                b64 = base64.b64encode(data).decode("utf-8")
                (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
                src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
                div = tag.format(src=src, mime_type=mime_type, css='')
                js = ''
        else:
            try:
                with silence_warnings(EMPTY_LAYOUT, MISSING_RENDERERS):
                    js, div, _ = notebook_content(model)
                html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
                data = encode_utf8(html)
                doc.hold()
            except:
                logger.disabled = False
                raise
            logger.disabled = False

        plot.document = doc
        if as_script:
            return div, js
        return data
1257588
def create_hlamphaplot(plotman, h, v, alpha, options):
    '''
    '''
    sizex, sizez = getfigsize(plotman)
    # create figure
    f, ax = plt.subplots(1, 3, figsize=(3 * sizex, sizez))
    if options.title is not None:
        plt.suptitle(options.title, fontsize=18)
        plt.subplots_adjust(wspace=1, top=0.8)
    cidh = plotman.parman.add_data(h)
    cidv = plotman.parman.add_data(v)

    cidr = plotman.parman.add_data(np.subtract(h, v))
    plot_pha(cidh, ax[0], plotman, 'horizontal', alpha,
             options.pha_vmin, options.pha_vmax,
             options.xmin, options.xmax, options.zmin, options.zmax,
             options.unit, options.pha_cbtiks, options.no_elecs,
             )
    plot_pha(cidv, ax[1], plotman, 'vertical', alpha,
             options.pha_vmin, options.pha_vmax,
             options.xmin, options.xmax, options.zmin, options.zmax,
             options.unit, options.pha_cbtiks, options.no_elecs,
             )
    plot_ratio(cidr, ax[2], plotman, 'hor - ver', alpha,
               options.rat_vmin, options.rat_vmax,
               options.xmin, options.xmax, options.zmin, options.zmax,
               options.unit, options.pha_cbtiks, options.no_elecs,
               )
    f.tight_layout()
    f.savefig('pha_hlam.png', dpi=300)
    return f, ax