def view_live(live, lang='EN'):
df_head = pd.DataFrame({'Cover': ['<img src="{0}" width=100 />'.format(live.cover)]})
df_head['Song Name'] = '<p style="color:{0};">{1}</p>'.format(attr_color[live.attr], live.name)
df_head['Group'] = live.group
df_head['Difficulty'] = live.difficulty
df_head['Total Note'] = live.note_number
df_head['Duration'] = live.duration
df_head.columns = ['<p>{0}</p>'.format(x) for x in list(df_head.columns)]
df = live.summary.copy()
pos_name = ['<p>{0}</p>'.format(x) for x in ['L1', 'L2', 'L3', 'L4', 'C', 'R4', 'R3', 'R2', 'R1']]
df.index = [pos_name[9-x] if type(x)==int else x for x in list(df.index)]
df = df.loc[pos_name+['total']]
df = df.applymap(lambda x: '<p>{0}</p>'.format(str(int(x)) if np.isclose(2*x,round(2*x)) else '{0:.3f}'.format(x))).transpose()
if lang=='CN':
df_head.columns = ['<p>{0}</p>'.format(x) for x in ['????', '????', '??', '??', 'Note??', '??']]
df.columns = list(df.columns)[:-1] + ['<p>??</p>']
df.index = ['<p>{0}</p>'.format(x) for x in ['??', '??', '??', '??', '??', '????', '????', '??????']]
elif lang=='EN':
df.index = ['<p>{0}</p>'.format(x) for x in ['tap', 'hold', 'swing', 'star', 'token', 'type weight', 'combo weight', 'weight fraction']]
return HTML(html_template.format(df_head.to_html(escape=False, index=False) + df.to_html(escape=False)))
python类HTML的实例源码
def print_frames(dataframes):
if not isinstance(dataframes, tuple):
return dataframes
border_style = u'\"border: none\"'
cells = [u'<td style={}> {} </td>'.format(border_style, df._repr_html_()) for df in dataframes]
table = '''<table style={}>
<tr style={}>'''.format(border_style, border_style) +\
'\n'.join(cells)+\
'''
</tr>
</table>'''
return HTML(table)
# from http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/#
def idv_help(line, cell=None):
DrilsdownUI.status("")
html = "<pre>idv_help Show this help message<br>" \
+ "run_idv<br>" \
+ "make_ui<br>" \
+ "load_bundle <bundle url or file path><br>" \
+ " If no bundle given and if set_ramadda has been called the bundle will be fetched from RAMADDA<br>" \
+ "load_bundle_make_image <bundle url or file path><br>" \
+ "load_catalog Load the case study catalog into the IDV<br>" \
+ "make_image <-publish> <-caption ImageName> <-capture (legend|window)> Capture an IDV image and optionally publish it to RAMADDA<br>" \
+ "make_movie <-publish> <-caption MovieName> <-capture (legend|window)> Capture an IDV movie and optionally publish it to RAMADDA<br>" \
+ "save_bundle <xidv or zidv filename> <-publish> <-embed> - write out the bundle and optionally publish to RAMADDA. If embed then embed the bundle xml into the notebook as a link<br>" \
+ "publish_bundle <xidv or zidv filename> - write out the bundle and publish it to RAMADDA<br>" \
+ "publish_notebook <notebook file name> - publish the current notebook to RAMADDA via the IDV<br>" \
+ "set_ramadda <ramadda url to a Drilsdown case study><br>" \
+ "create_case_study <case study name><br>" \
+ "set_bbox <north west south east> No arguments to clear the bbox<br></pre>"
DrilsdownUI.do_display(HTML(html))
def view_url_clicked(b):
DrilsdownUI.do_display(HTML("<a target=ramadda href=" + b.url + ">" + b.name + "</a>"))
display(IFrame(src=b.url, width=800, height=400))
def save_bundle(filename, publish=False, embed = False):
extra = ""
if filename is None:
filename = "idv.xidv"
if publish:
extra += ' publish="true" '
if not os.path.isabs(filename):
filename = os.path.join(os.getcwd() ,filename);
isl = '<isl><save file="' + filename + '"' + extra + '/></isl>'
result = Idv.run_isl(isl);
if not result.ok():
print("save failed")
return
if os.path.isfile(filename):
DrilsdownUI.status("Bundle saved:" + filename)
if embed:
bundle = open(filename, "rb").read()
bundle = b64encode(bundle).decode('ascii')
name = os.path.basename(filename);
html = '<a target=_bundle download="' + name +'" href="data:text/xidv;name=' + name +';base64,' + bundle +'">' + name +'</a>';
DrilsdownUI.do_display(HTML(html))
else:
DrilsdownUI.do_display(FileLink(filename))
return;
DrilsdownUI.status("Bundle not saved")
def publish(self, name, file=None, parent=None):
if "RAMADDA_USER" not in os.environ:
print("No RAMADDA_USER environment variable set")
return
if "RAMADDA_PASSWORD" not in os.environ:
print("No RAMADDA_PASSWORD environment variable set")
return
user = os.environ['RAMADDA_USER']
password = os.environ['RAMADDA_PASSWORD']
if parent is None:
parent = self.entryId
extra = ""
if file is not None:
extra += ' file="' + os.path.basename(file) + '" '
entry_xml = '<entry name="' + name + '" ' + extra + '/>'
with NamedTemporaryFile(suffix='.zip') as tmpZip:
with ZipFile(tmpZip.name, 'w') as myzip:
with NamedTemporaryFile(suffix='.xml') as tmpFile:
entries_file = open(tmpFile.name, 'w')
entries_file.write(entry_xml)
entries_file.close()
myzip.write(tmpFile.name, arcname='entries.xml')
if file is not None:
myzip.write(file)
files = {'file': open(tmpZip.name, 'rb')}
# TODO: change http to https
url = self.make_url("/entry/xmlcreate")
r = requests.post(url, files=files,
data={'group': parent, 'auth.user': user, 'auth.password': password, 'response': 'xml'})
root = ET.fromstring(r.text)
if root.attrib['code'] == 'ok':
for child in root:
display(HTML("Published file: " + self.make_entry_href(child.attrib['id'], name)))
else:
print('Error publishing file')
print(r.text)
def add_display_widget(self, row):
b = DrilsdownUI.make_button("Set URL", DrilsdownUI.set_url_clicked)
b.entry = self
row.append(b)
link = self.get_repository().make_url("/entry/show/?output=idv.islform&entryid=" + self.get_id())
row.append(HTML('<a target=ramadda href="' + link + '">Subset Bundle</a>'))
# Make the REPOSITORIES
def plot_state(self, **options):
"""Plot the current state of the inference algorithm.
This feature is still experimental and only supports 1d or 2d cases.
"""
displays = []
if options.get('interactive'):
from IPython import display
displays.append(
display.HTML('<span>Threshold: {}</span>'.format(self.state['threshold'])))
visin.plot_sample(
self.state['samples'],
nodes=self.parameter_names,
n=self.objective['n_samples'],
displays=displays,
**options)
def slider(self, div_id) :
#div_id = self.show(*args, **kwargs)
def change_frame(w) :
(updates, indices) = self.get_frame(w-1)
script = ''
for i in range(len(updates)) :
jupdate = json.dumps(updates[i], cls=utils.PlotlyJSONEncoder)
#pprint(jupdate)
script = script \
+ 'Plotly.restyle("{id}", {update}, [{index}]);'.format(
id=div_id,
update=jupdate, index = indices[i][1:-1])
#print(script)
update_str = (
''
'<script type="text/javascript">' +
'window.PLOTLYENV=window.PLOTLYENV || {{}};'
'window.PLOTLYENV.BASE_URL="' + 'https://plot.ly' + '";'
'{script}' +
'</script>'
'').format(script=script)
display(HTML(update_str))
interact((lambda frame : change_frame(frame)), frame=(1,len(self.frames)))
def __init__(self, shell):
super(PixiedustNodeMagics,self).__init__(shell=shell)
display(HTML(
"""
<div style="margin:10px">
<a href="https://github.com/ibm-cds-labs/pixiedust_node" target="_new">
<img src="https://github.com/ibm-cds-labs/pixiedust_node/raw/master/docs/_images/pdn_icon32.png" style="float:left;margin-right:10px"/>
</a>
<span>Pixiedust Node.js</span>
</div>
"""
))
# create Node.js sub-process
path = os.path.join(__path__[0], 'pixiedustNodeRepl.js')
self.n = Node(path)
ShellAccess.npm = Npm()
ShellAccess.node = self.n
def show_site(self, article, nwork, info):
"""Display site citation"""
text = "# Temp\n"
text += "insert('''"
text += citation_text(
self.citation_var, info,
ref=article.get('citation_id', ''),
backward=self.backward
) + "\n"
text += "''', citations='{}');".format(self.citation_file)
display_cell(text)
self.output_widget.clear_output()
with self.output_widget:
if self.to_display:
display("\n".join(self.to_display))
if 'div' in article:
display(HTML(repr(article['div'])))
elif 'name' in article:
print(article['name'])
self.to_display = []
def add_input_toggle():
from IPython.display import HTML, display
r = HTML('''
<script>
$( document ).ready(function () {
IPython.CodeCell.options_default['cm_config']['lineWrapping'] = true;
IPython.notebook.get_selected_cell()
IPython.toolbar.add_buttons_group([
{
'label' : 'toggle all input cells',
'icon' : 'fa-eye-slash',
'callback': function(){ $('div.input').slideToggle(); }
}
]);
});
</script>
''')
display(r)
return r
def toggle():
html = HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<a href="javascript:code_toggle()">toggle code cells</a>''')
return html
def display_source_ipython(self):
"""
Convenience method to print the loaded source file
as syntax highlighted HTML within IPython.
"""
from pygments import highlight
from pygments.lexers import SLexer
from pygments.formatters import HtmlFormatter
import IPython.display as display
with open(self.source_file) as f:
code = f.read()
formatter = HtmlFormatter()
return display.HTML('<style type="text/css">{}</style>{}'.format(
formatter.get_style_defs('.highlight'),
highlight(code, SLexer(), formatter)))
def show_graph(graph_def, max_const_size=32):
"""Visualize TensorFlow graph."""
if hasattr(graph_def, 'as_graph_def'):
graph_def = graph_def.as_graph_def()
strip_def = strip_consts(graph_def, max_const_size=max_const_size)
code = """
<script>
function load() {{
document.getElementById("{id}").pbtxt = {data};
}}
</script>
<link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
<div style="height:600px">
<tf-graph-basic id="{id}"></tf-graph-basic>
</div>
""".format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))
iframe = """
<iframe seamless style="width:1200px;height:620px;border:0" srcdoc="{}"></iframe>
""".format(code.replace('"', '"'))
display(HTML(iframe))
def __init__(self, names, initial_size, width=900, height=480):
# Call this once to raise an error early if necessary:
self._colors = colors.colors(len(names))
self._start = time.perf_counter()
self._initial_size = initial_size
self._sources = collections.OrderedDict([
(name, {
'hist': bm.ColumnDataSource(
data={'top': [], 'left': [], 'right': []}),
'pdf': bm.ColumnDataSource(
data={'x': [], 'y': []}),
'stddev': bm.ColumnDataSource(
data={'base': [], 'lower': [], 'upper': []}),
'median': bm.ColumnDataSource(
data={'x': [], 'y': []})
})
for name in names
])
self._width = width
self._height = height
self._plot = None
self._elapsed_rendering_seconds = 0.0
self._describe_widget = ipdisplay.HTML('')
def drawMolsByLabel(topicModel, label, idLabelToMatch=0, baseRad=0.5, molSize=(250,150),\
numRowsShown=3, tableHeader='', maxMols=100):
result = generateMoleculeSVGsbyLabel(topicModel, label, idLabelToMatch=idLabelToMatch,baseRad=baseRad,\
molSize=molSize, maxMols=maxMols)
if len(result) == 1:
print(result)
return
svgs, namesSVGs = result
finalsvgs = []
for svg in svgs:
# make the svg scalable
finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
+' '+str(molSize[1])+'"'))
return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader='Molecules of '+str(label),
namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))
# produces a svg grid of the molecules of a certain label and highlights the most probable topic
def drawMolsByTopic(topicModel, topicIdx, idsLabelToShow=[0], topicProbThreshold = 0.5, baseRad=0.5, molSize=(250,150),\
numRowsShown=3, color=(.0,.0, 1.), maxMols=100):
result = generateMoleculeSVGsbyTopicIdx(topicModel, topicIdx, idsLabelToShow=idsLabelToShow, \
topicProbThreshold = topicProbThreshold, baseRad=baseRad,\
molSize=molSize,color=color, maxMols=maxMols)
if len(result) == 1:
print(result)
return
svgs, namesSVGs = result
finalsvgs = []
for svg in svgs:
# make the svg scalable
finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
+' '+str(molSize[1])+'"'))
tableHeader = 'Molecules in topic '+str(topicIdx)+' (sorted by decending probability)'
return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader=tableHeader,\
namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))
# produces a svg grid of the molecules belonging to a certain topic and highlights this topic within the molecules
def interactive_html(self):
from IPython.display import display, HTML
uid = str(uuid.uuid4())
display(HTML(''.join(self.empty_table_generator(uid))))
internal_columns = self.get_internal_columns()
for key, report in self.get_reports():
js = '''
(function(){
var node = document.getElementById('diligent-%(uid)s-%(check_no)s-%(column_no)s');
var data = '%(data)s';
node.innerHTML = data;
if (!data) {
node.style.backgroundColor = '#eee';
}
}());
''' % {
'uid': uid,
'check_no': key[1],
'column_no': internal_columns.index(key[0]), # FIXME
'data': escape_js(''.join(self.render_messages(report)))
}
display({'application/javascript': js}, raw=True)
return ''
def _gen_summary(self, col_width=50):
pd.set_option('display.max_colwidth', -1)
song_name = '<p style="color:{0};">{1}</p>'.format(attr_color[self.live.attr], self.live.name)
df_head = pd.DataFrame({'Song Name': [song_name]})
df_head['Difficulty'] = self.live.difficulty
df_head['Score'] = int(self.global_status['cum_score'])
df_head['Cover Rate'] = '{0:.2f}%'.format(100*(self.simul_result['timing_sec'] <= self.simul_result['judge_end_time']).mean())
df_head['Max Combo'] = self.simul_result['combo'].max()
for accr in accuracy_list:
df_head[accr] = self.global_status['note_stat'][accr]
card = ['<img src="{0}" width={1} />'.format(icon_path(card.card_id, card.idolized), col_width) for card in self.card_list]
summary, keys = [], ['base_score', 'score', 'hp', 'judge', 'weak_judge']
for i in range(len(card)):
temp = {k:getattr(self.skill_tracker[i], 'cum_'+k) for k in keys}
temp['card'] = card[i]
summary.append(temp)
df = pd.DataFrame(summary, columns=['card']+keys)
df = df.append(pd.DataFrame(df.sum()).transpose())
df['base_score'] = df['base_score'].apply(lambda x: '<p>{0}</p>'.format(int(x)))
df['score'] = df['score'].apply(lambda x: '<p>{0}</p>'.format(int(x)))
df['hp'] = df['hp'].apply(lambda x: '<p>{0}</p>'.format(int(x)))
df['judge'] = df['judge'].apply(lambda x: '<p>{0}</p>'.format(round(x,1)))
df['weak_judge'] = df['weak_judge'].apply(lambda x: '<p>{0}</p>'.format(round(x,1)))
df.index = ['<p>{0}</p>'.format(x) for x in ['L1', 'L2', 'L3', 'L4', 'C', 'R4', 'R3', 'R2', 'R1', 'Total']]
df.loc['<p>Total</p>', 'card'] = ''
html_code = df_head.to_html(escape=False, index=False) + df.transpose().to_html(escape=False)
return HTML(html_code)
def show_live_list(group=None, attr=None, diff_level=None):
def match_func(x):
res = True
if group is not None: res &= x.group==group
if attr is not None: res &= x.attr==attr
if diff_level is not None: res &= x.diff_level==diff_level
return res
df = live_basic_data[live_basic_data.apply(lambda x: match_func(x), axis=1)].copy()
df['cover'] = df['cover'].apply(lambda x: '<img src="{0}" width=100 />'.format(x))
df['name'] = df.apply(lambda x: '<p style="color:{0};">{1}</p>'.format(global_var.attr_color[x['attr']], x['name']), axis=1)
df = df[['cover', 'name', 'diff_level', 'note_number', 'diff_star']]
df.columns = ['<p>{0}</p>'.format(x) for x in df.columns]
return HTML(df.to_html(escape=False, index=False))
def show_markup(text, spans, index=False):
from IPython.display import HTML, display
html = ''.join(format_markup(text, spans, index=index))
display(HTML(html))
def display(self, columns=[], msg=None):
data = self.data if len(self.data) <= 100 else self.data[:49] + [['...'] * (len(self.data[0]))] + self.data[-49:]
table_str = HTMLTable([columns] + data, self.id_)._repr_html_(n_rows=100, length=len(self.data))
table_str = table_str.replace('<table', '<table class="table-striped table-hover table-bordered"').replace("'", "\\'").replace('\n','')
display(
HTML(
"""
<script type="text/Javascript">
$('#dbinfo{id}').append('{msg}');
$('#table{id}').append('{table}');
</script>
""".format(msg=str(msg), table=table_str, id=self.id_)
)
)
def print_html(html):
display(HTML(html))
def notebook_to_nbviewer():
js = _js_callback_open + _js
html = '<script type="text/javascript">'
html += js
html += '</script>'
html += '<b>nbviewer will open in a new tab in 20 seconds .....</b>'
return display(HTML(html))
def get_sys_info():
"""Display info on system and output as nice HTML"""
spacer = "<tr><td> </td><td> </td></tr>"
html = '<h3>System Information for {}</h3>'.format(platform.node())
html += '<table>'
html += '<tr><td align="left">Python Executable</td>'
html += '<td>{}</td></tr>'.format(sys.executable)
html += '<tr><td>Kernel PID</td><td>{}</td></tr>'.format(
psutil.Process().pid)
mem = psutil.virtual_memory()
html += '<tr><td>Total System Memory</td>'
html += '<td>{:.4} Mb</td></td>'.format(mem.total/1024**3)
html += '<tr><td>Total Memory Used</td>'
html += '<td>{:.4} Mb</td></td>'.format(mem.used/1024**3)
html += '<tr><td>Total Memory Free</td>'
html += '<td>{:.4} Mb</td></td>'.format(mem.free/1024**3)
html += '<tr><td>Number of CPU Cores</td><td>{}</td></tr>'.format(
psutil.cpu_count())
html += '<tr><td>Current CPU Load</td><td>{} %</td></tr>'.format(
psutil.cpu_percent(1, False))
html += '</table>'
return HTML(html)
def show_kernels():
"""Show all IPython Kernels on System"""
total_mem = psutil.virtual_memory().total
html = ('<h3>IPython Notebook Processes on {}</h3>'
'<table><tr>'
'<th>Username</th><th>PID</th><th>CPU Usage</th>'
'<th>Process Memory</th><th>System Memory Used</th><th>Status</th>'
'</tr>').format(platform.node())
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'username', 'cmdline',
'memory_info', 'status'])
except psutil.NoSuchProcess:
pass
else:
if any(x in pinfo['cmdline'] for x in ['IPython.kernel',
'ipykernel_launcher']):
html += '<tr>'
html += '<td>{username}</td><td>{pid}</td>'.format(**pinfo)
p = psutil.Process(pinfo['pid']).cpu_percent(0.1)
html += '<td>{}%</td>'.format(p)
html += '<td>{:.4} Mb</td>'.format(pinfo['memory_info'].vms /
1024**3)
html += '<td>{:.3}%</td>'.format(100 *pinfo['memory_info'].vms /
total_mem)
html += '<td>{}</td>'.format(pinfo['status'])
html += '</tr>'
html += '</table>'
return HTML(html)
def async_run(self, line, cell=None):
"""Run code into cell asynchronously
Usage:\\
%async_run <source> (cell content)
"""
if cell is None:
code_to_run = line
else:
code_to_run = cell
session_id = str(uuid4())
connection_id = format_ws_connection_id(PY_ROLE, session_id)
try:
_ = urlopen(connection_string(web_socket=False, extra='ping'))
except URLError:
print("Connection to server refused!", end=' ')
print("Use %async_run_server first!")
else:
connector = WSConnector(connection_id, code_to_run, self.shell)
connector.connect()
html_output = LIGHT_HTML_OUTPUT_CELL.format(session_id=session_id)
js_code = JS_WEBSOCKET_CODE.replace('__sessionid__', session_id)
js_code = js_code.replace('__connection_id__', format_ws_connection_id(JS_ROLE,
session_id))
html_output += js_code
return HTML(html_output)
def show(self):
"""Show the viewer.
"""
viewer_url = self.get_server_url() + '/neuroglancer' + '#!' + self.get_encoded_state()
large_html = "<style>.container { width:100% !important; }</style>" if self.large else ""
return HTML(large_html + "<iframe src=\"" + viewer_url + "\" width=\"100%\" height=\"1024px\"><\iframe>")
def enable_mpl_offline(resize=False, strip_style=False,
verbose=False, show_link=True,
link_text='Export to plot.ly', validate=True):
"""
Convert mpl plots to locally hosted HTML documents.
This function should be used with the inline matplotlib backend
that ships with IPython that can be enabled with `%pylab inline`
or `%matplotlib inline`. This works by adding an HTML formatter
for Figure objects; the existing SVG/PNG formatters will remain
enabled.
(idea taken from `mpld3._display.enable_notebook`)
Example:
from plotly.offline import enable_mpl_offline
import matplotlib.pyplot as plt
enable_mpl_offline()
fig = plt.figure()
x = [10, 15, 20, 25, 30]
y = [100, 250, 200, 150, 300]
plt.plot(x, y, "o")
fig
```
"""
init_notebook_mode()
ip = IPython.core.getipython.get_ipython()
formatter = ip.display_formatter.formatters['text/html']
formatter.for_type(matplotlib.figure.Figure,
lambda fig: iplot_mpl(fig, resize, strip_style, verbose,
show_link, link_text, validate))
```