Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def setUp(self):
self.tmpdir = tempfile.TemporaryDirectory()
nb = new_notebook()
nb.cells.append(new_markdown_cell(u'Created by test ³'))
cc1 = new_code_cell(source=u'print(2*6)')
cc1.outputs.append(new_output(output_type="stream", text=u'12'))
cc1.outputs.append(new_output(output_type="execute_result",
data={'image/png': png_green_pixel},
execution_count=1,
))
nb.cells.append(cc1)
with io.open(pjoin(self.tmpdir.name, 'testnb.ipynb'), 'w',
encoding='utf-8') as f:
write(nb, f, version=4)
def test_contents_manager(self):
"make sure ContentsManager returns right files (ipynb, bin, txt)."
nbdir = self.notebook_dir
nb = new_notebook(
cells=[
new_markdown_cell(u'Created by test ³'),
new_code_cell("print(2*6)", outputs=[
new_output("stream", text="12"),
])
]
)
with io.open(pjoin(nbdir, 'testnb.ipynb'), 'w',
encoding='utf-8') as f:
write(nb, f, version=4)
with io.open(pjoin(nbdir, 'test.bin'), 'wb') as f:
f.write(b'\xff' + os.urandom(5))
f.close()
with io.open(pjoin(nbdir, 'test.txt'), 'w') as f:
f.write(u'foobar')
f.close()
def setUp(self):
self.tmpdir = tempfile.TemporaryDirectory()
nb = new_notebook()
nb.cells.append(new_markdown_cell(u'Created by test ³'))
cc1 = new_code_cell(source=u'print(2*6)')
cc1.outputs.append(new_output(output_type="stream", text=u'12'))
cc1.outputs.append(new_output(output_type="execute_result",
data={'image/png': png_green_pixel},
execution_count=1,
))
nb.cells.append(cc1)
with io.open(pjoin(self.tmpdir.name, 'testnb.ipynb'), 'w',
encoding='utf-8') as f:
write(nb, f, version=4)
elif not source.startswith("%") or \
source.startswith("%sh") or \
source.startswith("%spark.dep") or \
source.startswith("%pyspark") or \
source.startswith("%spark") or \
source.startswith("%sql"):
count_cells_code += 1
execution_count += 1
outputs = []
results = paragraph.get("results", {})
msgs = results.get("msg", [])
for msg in msgs:
if msg["type"] == "TEXT":
outputs.append(nbf.v4.new_output("execute_result", {'text/plain': [msg["data"]]},
execution_count=execution_count))
elif msg["type"] == "TABLE":
outputs.append(nbf.v4.new_output("execute_result", {'text/plain': [msg["data"]]},
execution_count=execution_count))
elif msg["type"] == "HTML":
outputs.append(nbf.v4.new_output("execute_result", {'text/html': [msg["data"]]},
execution_count=execution_count))
else:
print("Warning: unsupported output type: '{}'".format(msg["type"]))
print(msg)
cell = nbf.v4.new_code_cell(source=source, execution_count=execution_count, outputs=outputs)
self.nb['cells'].append(cell)
else:
error = PapermillExecutionError(
exec_count=cell.execution_count,
source=cell.source,
ename=output.ename,
evalue=output.evalue,
traceback=output.traceback,
)
break
if error:
# Write notebook back out with the Error Message at the top of the Notebook.
error_msg = ERROR_MESSAGE_TEMPLATE % str(error.exec_count)
error_msg_cell = nbformat.v4.new_code_cell(
source="%%html\n" + error_msg,
outputs=[
nbformat.v4.new_output(output_type="display_data", data={"text/html": error_msg})
],
metadata={"inputHidden": True, "hide_input": True},
)
nb.cells = [error_msg_cell] + nb.cells
write_ipynb(nb, output_path)
raise error
def encode_plot_cell(cell, source, result, figure):
img = io.BytesIO()
figure.savefig(img)
img.seek(0,0)
img = base64.b64encode(img.read())
output_cell = nbf.v4.new_code_cell(
source,
outputs=[
nbf.v4.new_output(
'execute_result',
{
'text/plain': [result]
},
execution_count=cell
),
nbf.v4.new_output(
'display_data',
{
'text/plain': [repr(figure)],
'image/png': img.decode()
}
)
]
)
return output_cell
def append_code(self, input, output=None, image=None, metadata=None):
input = self._code_filter(input)
cell = nbf.v4.new_code_cell(input,
execution_count=self._count,
metadata=metadata)
if output:
cell.outputs.append(nbf.v4.new_output('execute_result',
{'text/plain': output},
execution_count=self._count,
metadata={},
))
if image:
# TODO
raise NotImplementedError("Output images not implemented yet.")
self._nb['cells'].append(cell)
self._count += 1
def encode_figure(figure, **kwargs):
img = io.BytesIO()
figure.savefig(img, **kwargs)
img.seek(0,0)
return nbf.v4.new_output(
'display_data',
{
'text/plain': [repr(figure)],
'image/png': base64.b64encode(img.read()).decode()
}
def encode_dataframe(df, n, **kwargs):
return nbf.v4.new_output(
'execute_result',
{
'text/plain': [df.to_string()],
'text/html': [df.to_html(**kwargs)]
},
execution_count=n
)