Disable Jupyter Notebook automatic hyperlink - jupyter-notebook

In my notebook, I print some data from scraped web pages. Some of these are hyperlinks without tags e.g. https://stackoverflow.com. Unfortunately, Notebook prints these out as an actual hyperlink (i.e. wraps it in tags) on the output page and shortens it. (So the final result in HTML looks like this: https://stacko....) The field is set to code, but this still happens. Is there a way to disable this behaviour?

Solution:
Enter the following text in the empty cell of your Jupyter notebook:
%%javascript
Jupyter.utils.autoLinkUrls = function (txt) {
return txt;
}
Explanation:
The ability to locate URLs in text output and convert them to hyperlinks appeared in IPython notebook (a Jupyter's predecessor) as a result of a merge request in Oct' 2012. Since then every piece of output is scanned for URLs and each found URL is replaced with an anchor <a href=.../>. There's no easy way to alter this behavior because function autoLinkUrls(...) doesn't provide any configuration parameters.
So, the only way to disable URL "autolinking" is to simply replace JavaScript function autoLinkUrls, which is exposed through global Jupyter object, and %%javascript magic command makes the job done.

Related

is there a way to read the contents of the last jupyter markdown cell as a string?

I'm using jupyter and pandas read_sql, this works fine but looks ugly.
for instance I have a query:
SELECT *
FROM table_a AS a
LIMIT 10;
I could show it nicely in a markdown cell as so:
``` mysql
SELECT *
FROM table_a AS a
LIMIT 10;
```
and I could execute it in a code cell as so:
pd.read_sql('SELECT * FROM table_a AS a LIMIT 10;', conn)
this involves copy/paste and displaying the query twice (not too good if I want to simply export my notebook to a pdf report)
is there a way to avoid the duplication by reading the markdown text into a string python variable, or any other way?
The cellmagic answer cited by #Micah Kornfield in the question comments may be a good fit for many situations. In the question however it is said that it is desirable to avoid duplicates. Let's imagine that the SQL is huge and we don't want see the same query more than once.
Unfortunatelly right now in 2021 there's no easy solution for this. In a jupyter notebook there are two worlds, the backend which is the kernel and in our case runs python, and the frontend which runs javascript. Only javascript sees the markdown cells. It is possible to make the backend and frontend communicate with each other, those methods are usually a little hacky, but anyway we will rely on some of them.
I have written a script that does our job in two different ways, which will probably bring similar results. I will call those methods the file read method and the javascript method.
First, please save the following file markdown.py in the same folder as the ipython (we are using a separate file because you specified that your notebook willl eventually go to a report and it is undesirable to have this script together with the notebook):
from IPython.display import Javascript
from urllib.parse import unquote
from json import loads as jsonloads
def markread(cellnumber,notebookname=None,callbackvar=None):
try:
if type(cellnumber) is int:# maybe check if (varname in globals()):
if callbackvar is not None and type(callbackvar) is str:
return Javascript("const mdtjs = Jupyter.notebook.get_cells().filter(c=>c.cell_type==\"markdown\")["+str(cellnumber)+"].get_text(); IPython.notebook.kernel.execute(\"mdtp = unquote('\"+encodeURI(mdtjs)+\"');mdtp=mdtp[mdtp.find('\\\\n',mdtp.find('```'))+1:min(mdtp.rfind('\\\\n'),mdtp.rfind('```'))].strip();"+callbackvar+"=mdtp;del mdtp\");")
if notebookname is not None and type (notebookname) is str:
if not notebookname.endswith('.ipynb'):
notebookname += '.ipynb'
with open(notebookname) as f:
j = jsonloads(f.read())
mdts = [''.join(c['source'][1:]).strip().strip('`').strip() for c in j['cells'] if c['cell_type']=='markdown']
return mdts[cellnumber]
except:
return None
return None
Now back to the notebook, to load the script, you have to import it:
from markdown import markread, unquote
The unquote is needed to use the javascript method, otherwhise you can skip it.
1. File read method:
Usage:
marktext = markread(2, notebookname='mynotebookname')
Here marktext will get the value from the third markdown cell in the mynotebookname (third because we live in a zero-indexed world, so 2 means third; if you skip '.ipynb' extension in the notebookname as in this case it will be automatically appended). Important - this method reads the notebook file writen on disk and not the hot state of things. If you changed anything since last save, things may go wrong.
2. Javascript method:
Usage:
markread(1, callbackvar='marktext')
Here we write the value of our second markdown cell to a variable called marktext. Javascript method is trickier - it is async, so we have to send the name of the variable that we want to write to (must be a string representing its name, not the variable itself). Is is important to know also that markread must be the last command in the cell due to a limitation in javascript invoking.
How it works
Internally, the file read method just reads the notebook file which is json, picks the value from 'cells' and filters out the ones which are markdown.
The javascript method however is more complex. It invokes JS because JS has access to the cells including markdown, so JS reads cells values (from the Jupyter.notebook.get_cells), filters the markdown ones, invoke python back and send back those markdown cells - url enconded. Those encoded cells are decoded back and assigned to the callbackvar. In both methods I made some assumptions that may not be correct about trimming the start and the end of the cell value (the ``` and whitespaces).
There are ways to improve the code, for example making it auto detect the notebook name for the file read method, but it involves even more hacks, relying again on javascript to get the notebook name or making an call to the api on port 8888, but having to deal with session password. I believe the most important is covered already by our script. If one method does not work, you will probably still have the other.

Which analyze-suspend should I foresee for a checkbox in a temporary table inside a browser?

I am working with Progress-4GL, release 11.6, appBuilder and procedure editor. I can't upgrade to a more recent IDE.
I have created a temporary table, containing a LOGICAL field (shown as a checkbox), and I'm showing the values of those checkboxes inside a browser object.
Now I need the following piece of source code:
ON LEAVE OF temptable.checkbox_attribute IN BROWSE browser_object
DO: ...
END.
The problem is: now I would like to open this file in appBuilder, but as there are no ANALYZE-SUSPEND and ANALYZE-RESUME lines around it, the appBuilder will remove those lines.
In order to avoid this, I'd like to write those lines myself, but how can I do that?
For your information: in the appBuilder it is only possible to add events to existing statical objects, so adding events to temporary tables can't be done.
I already tried copying such a line from another event, but as the mentioned _CONTROL ... objects don't correspond, this doesn't work.
You don't need &ANALYZE-SUSPEND / &ANALYZE-RESUME. Just put the whole trigger in the main block of the program, after
&ANALYZE-SUSPEND _UIB-CODE-BLOCK _CUSTOM _MAIN-BLOCK B-table-Win
(Or just navigate to section Main Block in the Section Editor of the AppBuilder.)
The AppBuilder does not recognize this as a separate user interface trigger.

How do you flip whole Docs horizontally 180* with the CSS command rotateY(180deg)?

I can get basic html text to flip 180*, but I'd like to know how to get a whole Doc in my Drive file to flip using a standalone script (so I can do it repeatedly). I'm aware I can get a doc, open the scripts editor and then use my flippin' project to flip the doc I called, but I don't know what the syntax looks like. My first flippin' success was pasting text into the .html file as simply as possible and using:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Page');
getContent()
}
I just test ran it from the dialog box as a web app. But I'm interested in building this one command feature out into several different domains to get experience with the variety of possibilities available in GAS. Anyone care to tutor me? Please?!...

How to simulate paste(CTRL + V) using AUTO IT in Word Document

Objectives -
Open the target app using AutoIy
Take a printscreen (ALT + PRTSCREEN) of the opened app(step 1)
Open a new word document
Paste the screenshot on word document
Issue:
I am able to complete the first two step, however I am not able to paste the screenshot in Word document.
Root Cause
I am able to take the print screen using SEND ("!{PRINTSCREEN}") and open word document using UDF _WORD_DOCADD, but I am not able to paste from clipboard. The issue is, when I am using WinWaitActive to activate the document, the document is still not active and hence SEND ("^V") is not working.
You are using Send incorrectly to send the Ctrl+V. With a capitol V, it will be interpreted by AutoIt as Ctrl+Shift+V (see helpfile for details). Instead what you want to use is Send("^v").
WinWaitActive does not activate the document, it simply waits for it to become active, use WinActivate to activate word.
The correct way to paste though is to use the word com object, something like: $oWord.Activedocument.Range.paste. That will work without word being active or visible.
Also, there are better ways to screenshot than sending Alt+Printscreen.
All these steps are very well documented, and have been done many times before.
I found a way to solve my problem. Steps followed are -
Simulate ALT + PRNTSCRN
Open Clipboard
GetData from Clipboard as BITMAP
Save the data as JPG using GDIPLUS_IMAGE_SAVETOFILE
Use DOCADD to open new document and _Word_DocPictureAdd to save the image to word document.

Insert programming code in a Lyx document

What is the best way of inserting python/C++ code in a Lyx document? The code is small examples less than 20 lines.
My Lyx document is using the Book document class.
Orjanp
I prefer to insert the listings as a child document, so the code is grabbed directly from a file that you can further edit and keep updated (you avoid to duplicate an information and maintenance is a lot easier).
To do this in Lyx:
Insert->File->Child document
Then in the window that will appear change the type to program listing and configure it as you need, for example you could want to enter the parameter language=Python (you can type a ? to view all the parameters).
A set of parameters I usually use is:
breaklines=true //--> breaks lines to margin
captionpos=b //--> caption at the bottom of the listing (default is "t")
frame=tb //--> frame at the top and at the bottom of the listing
language=Python //--> syntax highlighting for python
There should be an Insert -> Program Listing option. That uses listings Latex package, so you should have that installed. The support seems to have been added in Lyx 1.5, and from their screenshot, it seems it gives you a lot of customization options.
The insert->Program Listing feature works great. I just want to add that if you are on Mac, and try to directly paste, using command+V or right-click+paste, a block of code into the program listing, the whitespace will not be preserved, and you have to manually insert the whitespace by typing tabs, returns, etc.
A very easy way to get around this is is to paste using shift+command+V. This preserves all the whitespace of your original source code.

Resources