Jupyter Notebook: command for hide the output of a cell? - ipython

In my notebook, I have a cell returning temp calculation results. It's a bit long, so after it is run, I want to hide it and when needed, to show it.
To do it manually, I can double click the left side of the output, to hide it
After double click
But is there any way I can do this by code? For example,
the last line of the cell, use a command like %%hide output, and the output would be hidden after finished running.
Additionally, can I get this feature in output HTML?

Add ; by the end of the cell to hide the output of that cell.

In the newer versions(5.0.0 at the time I'm writing this), pressing o in the command mode hides the output of the cell in focus. The same happens if you triple click in front of the output.
o is
the first letter in the word "output" or
lower case of 15th letter in the alphabet

You can add %%capture to the beginning of the cell.
Jupyter provides a magic cell command called %%capture that allows you to capture all of to outputs from that cell.
You can use it like this:
%%capture test
print('test')
test.stdout => 'test\n'
https://ipython.readthedocs.io/en/stable/interactive/magics.html

In newer versions of Jupiter Notebook, select the desired cell, make sure you're in command mode and then on the menubar press Cell > Current Outputs. You have then three options:
Toggle (press O in the command mode to apply the same effect)
Toggle Scrolling (the default output)
Clear (to clear the output all together)
Image to Menubar Options
Additionally, you can apply the same effect to all the cells in your document if you chose All Output instead of Current Output.

Not exactly what you are after, but the effect might be good enough for your purposes:
Look into the %%capture magic (https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb). It lets you assign that cell output to a variable. By calling that variable later you could see the output.

Based on this, I just came up with this for myself a few minutes ago:
%%javascript
$('#maintoolbar-container').children('#toggleButton').remove()
var toggle_button = ("<button id='toggleButton' type='button'>Show Code</button>");
$('#maintoolbar-container').append(toggle_button);
var code_shown = false;
function code_toggle()
{
if (code_shown)
{
console.log("code shown")
$('div.input').hide('500');
$('#toggleButton').text('Show Code');
}
else
{
console.log("code not shown")
$('div.input').show('500');
$('#toggleButton').text('Hide Code');
}
code_shown = !code_shown;
}
$(document).ready(function()
{
code_shown=false;
$('div.input').hide();
});
$('#toggleButton').on('click', code_toggle);
It does have a glitch: each time you run that cell (which I put at the top), it adds a button. So, that is something that needs to be fixed. Would need to check in the maintoolbar-container to see if the button already exists, and then not add it.
EDIT
I added the necessary piece of code:
$('#maintoolbar-container').children('#toggleButton').remove()

You can use the notebook utils from https://github.com/google/etils:
!pip install etils[ecolab]
from etils import ecolab
with etils.collapse():
print('This content will be hidden by default')
It will capture the stdout/stderr output and display it a some collapsible section.
Internally, this is more or less equivalent to:
import contextlib
import html
import io
import IPython.display
#contextlib.contextmanager
def collapse(name: str = ''):
f = io.StringIO()
with contextlib.redirect_stderr(f):
with contextlib.redirect_stdout(f):
yield
name = html.escape(name)
content = f.getvalue()
content = html.escape(content)
content = f'<pre><code>{content}</code></pre>'
content = IPython.display.HTML(
f'<details><summary>{name}</summary>{content}</details>')
IPython.display.display(content)
The section is collapsed by default, but I uncollapsed it for the screenshot.

To prepend a cell from getting rendered in the output, in the notebook, by voilo or voila gridstack, just put in the first line of each cell to hide the output:
%%capture --no-display
reference in ipypthon documentation

For Windows,
in Jupyter Notebook, click the cell whose output you want to hide.
Click Esc + o for toggling the output

So I totally understand. When you have like 100 different plot and when you do the "Restart & Run All" those ugly plots all show up again
what you can do is ctrl+A and press o it will all of a sudden hide all your cells!!! For you to collapse automatically, you may need to use JupyterLab (another level after JupyterNotebook) but still, by doing ctrl+A then o you will be able to collapse all the results!!!
ctrl+A --> select ALL (make sure to click outside of coding box before you do it!)
o --> toggle collapse

If you don't mind a little hacking, then you may write a simple script for inverting the "collapsed" attribute of each cell from false to true
in the notebook .ipynb file (which is a simple JSON file).
This is however may fail in the future if a the .ipynb format changes.

Related

Using vscode with Jupyter extension, how to find/replace text within a notebook cell [duplicate]

As the title says, how to find and replace text inside a single jupyter cell when using the jupyter extension in Visual Studio Code? I am familiar with ctr+h but that will replace all the occurrences in the entire jupyter notebook file. This is a really important feature for me, as I am using it a lot in jupyter on the browser.
2023-02-09 update
For the most updated VSCode, select something you would like to replace, and then F2.
Original answer
F3 do the trick. It first shows the "Find" widget for a single cell. Then click the triangle on the left, which will be expanded to a "Replace" widget.
You can select the first occurrence and then use Ctrl+D. It will select the next occurence in the cell. Repeat that until you go back to the first ocurrence and then type the new value. It will replace all the values your circled on.
In case you have changed that keyboard shortcut or if it is different you can find the correct one:
try select a cell and use Ctrl+g as I just found out accidentally.

Jupyter Lab Max Number of Outputs Trimmed

How to change Jupyter Lab default behaviour trimming higher number of outputs.
The message in the middle of outputs says:
Output of this cell has been trimmed on the initial display.
Displaying the first 50 top and last bottom outputs.
Click on this message to get the complete output.
There is maxNumberOutputs parameter in Jupyter Lab source code, but I didn't found any method to change it.
You can change maxNumberOutputs in settings: click on Menu bar → Settings → Advanced Settings Editor → Notebook → set maxNumberOutputs in the User Preferences tab, like:
{
"maxNumberOutputs": 100
}
save, and reload.
Using jupyter lab path to find the "User settings" path, you can write from the notebook directly by executing this writefile magic from within a cell:
%%writefile <your-jupyter-lab-path>/user-settings/#jupyterlab/notebook-extension/tracker.jupyterlab-settings
{
"maxNumberOutputs":100
}
This path may be slightly different depending on your environment and Jupyterlab version, so probably best to manually change it using this answer and then finding the file that was modified. After that you can place this code before the %%writefile command to ensure that this works on your next Jupyter session without manually going to advanced settings in the menu bar:
!file="<your-jupyter-lab-path>/user-settings/#jupyterlab/notebook-extension/tracker.jupyterlab-settings" && mkdir -p "${file%/*}" && touch "$file"
Finally, to ensure that you have correctly changed the values,use this code to test your output:
from IPython.display import display
[display(i) for i in range(75)]
where 75 outputs should not be trimmed. If it is, then try refreshing the page to re-apply the settings.

Sublime Text 3: Keep entire lines selected when indenting with tab

I have an issue that is driving me insane with Sublime Text 3. When I select multiple lines by clicking on the side of the line and dragging, I then hit tab to correct the indentation, but then I want to move the entire line to another spot except I have to re-select it because the first line is only selected from where the text starts, not where the line starts.
Let's see if I can illustrate this... Below is the lines I have:
Text Line 1
Text Line 2
I select them (selection shown using *)
*Text Line 1
Text Line 2*
I indent the lines and now the selection looks like this:
*Text Line1
Text Line 2*
Notice the selection starts with the text. I want the selection to stay at the beginning of the line like this:
* Text Line 1
Text Line 2*
I have searched everywhere but apparently I'm the only one that is bothered by this. Every other code editor I have used does it the way I want.
You can achieve this will a small Python plugin:
Tools -> Developer -> New Plugin...
Replace the contents with the following:
import sublime
import sublime_plugin
class IndentSelectWholeFirstLineEventListener(sublime_plugin.EventListener):
def on_post_text_command(self, view, command_name, args):
if command_name == 'indent':
if all(not sel.empty() for sel in view.sel()):
if all(view.line(sel.begin()) != view.line(sel.end()) for sel in view.sel()):
new_selections = []
for sel in view.sel():
new_selections.append(sel.cover(view.line(sel.begin())))
view.sel().clear()
view.sel().add_all(new_selections)
Save it in the folder ST suggests, as fix_selection_after_indent.py
How this works:
Immediately after the indent command is executed, if all the selections are not empty, and they all span multiple lines, extend the selections to cover the entire first line of each selection.
There's a fix...
There is a plugin called FixSelectionAfterIndent, I just found it (again) because SublimeText4 has the same problem and I already forgot how I fixed it in ST3. So anyone looking for a solution to this (veeeeeeeery annoying) problem, here it is. (You can install it via Package Control, but I like to put links in my answers, for no particular reason.)
https://packagecontrol.io/packages/FixSelectionAfterIndent

Dynamically updating text in Matlab GUI

I think it should be pretty simple what I want to do, basically I have one edit box that displays a value in percentages and another that I want to update to display raw values. I've tried using the following code under the edit1 (percent) callback:
currentKey = str2num(get(gcf,'CurrentKey'));
percent = str2num(get(handles.edit1,'String'));
if ~isnan(currentKey) && ~isnan(percent) && 0<=percent && percent<=100
set(handles.edit2,'String',num2str(2*percent))
end
But it will only update the second edit box if I first click outside of the first one. Anyone have an idea of what I should be doing?
Thanks!
I think this link should help you:
How can I make the text that I enter into an edit text box update dynamically?
Solution:
This enhancement has been incorporated in Release 2011a (R2011a). For previous product releases, read below for any possible workarounds:
This is expected behavior of the Edit Box UICONTROL in MATLAB.
You can try using the 'keypressfcn' to grab the keyboard input. The attached two files demonstrate the ability of real-time text update. As you enter text into the upper edit box, the text will be copied to the edit box beneath it as you enter.
Please download the following two files:
test_keypressfcn.m
test_keypressfcn.fig
Execute the program.
A GUI will appear. Enter text in the upper edit box displayed in the GUI.
Observe the text in the lower editbox is updated dynamically or in real-time as you enter test in the upper edit box.
Please note that this will work only for text that is continuously entered in the editbox. If you type in between words already entered in the editbox the gui will not perform as expected. You will need to implement logic similar to the one in this example to get the behavior that you desire.

How do you retrieve the selected text in MATLAB?

MATLAB has several selection-sensitive capabilities. For example, if you select some text and press F9, it evaluates your selection. (Unless you've remapped your keyboard settings.)
I'd like to be able to replicate this functionality with for a shortcut. So, for example, I want to click a shortcut that displays the current selection. My shortcut callback would be disp(GetSelection()).
But what goes into GetSelection?
Thanks to #Yair Altman's undocumented Matlab, I was able to figure out the java commands to make this work.
Put this in a shortcut (or a function that is called by the shortcut):
%# find the text area in the command window
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
try
cmdWin = jDesktop.getClient('Command Window');
jTextArea = cmdWin.getComponent(0).getViewport.getComponent(0);
catch
commandwindow;
jTextArea = jDesktop.getMainFrame.getFocusOwner;
end
%# read the current selection
jTxt = jTextArea.getSelectedText;
%# turn into Matlab text
currentSelection = jTxt.toCharArray'; %'
%# display
disp(currentSelection)
I don't believe there is any way to control or read the selection from the Matlab text editor, there is no mention of such an API on the Mathworks website (at least from a quick search on Google). If you want this functionality to enable more advanced text editing, then you might want to consider setting the .m file editor to an external editor (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/brxijcd.html). It may be possible to read the selection from a UIcontrol in a custom GUI, but I don't think this is what you want.
In case you want to use something like this but with text highlighted in the editor rather than in the command window.
I use the following code in order to be able to quickly check the nnz() of a variable, although you can change the code in the nested try-catch to whatever you need.
Lastly, I created a shortcut with this code in the top right of Matlab, which I access quickly by pressing Alt-1.
try
activeEditor = matlab.desktop.editor.getActive;
currentSelection = activeEditor.SelectedText;
try
eval(sprintf('val = nnz(%s);',currentSelection))
disp(sprintf('>> nnz(%s) = %s',currentSelection,num2str(val)))
catch ex
disp(ex.message)
end
catch ex
disp(ex.message)
end