How to Enable MathJax Upgreek in jupyter/ipython notebook? - ipython
I have reviewed various related questions including
How do I get MathJax to enable the mhchem extension in ipython notebook
IPython (Jupyter) MathJaX preamble
but I cannot get it to work...
My test case is simply
from IPython.display import display, HTML, Math, Latex
display(Math(r'\uppi'))
expecting upright $\pi$ but currently getting just '\uppi' back raw.
I have tried the following using cell magic
%%javascript
<script type="text/Javascript">
MathJax.Hub.Config({
loader: {load: ['[tex]/upgreek']},
tex: {packages: {'[+]': ['upgreek']}}
});
</script>
which generates Javascript Error: Unexpected token '<'
%%javascript
MathJax.Hub.Config({
loader: {load: ['[tex]/upgreek']},
tex: {extensions: ['require.js'], packages: {'[+]': ['upgreek']}}
});
which throws no error but doesn't seem to have any effect
%%javascript
window.MathJax = {
loader: {load: ['[tex]/upgreek']},
tex: {packages: {'[+]': ['upgreek']}}
};
which also does not seem to have the desired effect
Question: I don't want to modify configuration/javascript files outside the notebook. How can I enable MathJax upgreek dynamically in a jupyter notebook?
(Currently on jupyterlab 3.2.2, python 3.8.10 under Windows 10)
This does not address the OP's fundamental issue, which relates to the control of the installation of MathJax extensions in jupyter, but it does address the objective: to alter the rendered appearance of greek symbols (but can be applied to other font-related needs as well)
Updated
The following will create TeX macros for all upper and lower case greek characters, as also available in Upgreek if it could be installed.
from IPython.display import display, Math
# Using codes from https://unicode-table.com/en/sets/greek-symbols/, create dictionaries of unicodes keyed by character names
grLcUpChars = [rf'\unicode{{{code}}}' for code in range(0x3B1, 0x3CA) if code != 0x3C2] # omit 'final sigma'
grUcUpChars = [rf'\unicode{{{code}}}' for code in range(0x391, 0x3AA) if code != 0x3A2] # omit omitted code for 'final sigma' in uppercase
grCharNames = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda',
'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']
zipIt = zip(grCharNames, grLcUpChars)
grLcUpDict = dict(zipIt)
zipIt = zip(grCharNames, grUcUpChars)
grUcUpDict = dict(zipIt)
# Generate the MathJax code to create 'macro' definitions for upright greek characters
# See e.g. https://docs.mathjax.org/en/latest/input/tex/macros.html
# Paste output text from $ to $ inclusive into a markdown cell and execute it
print('$')
for grCharName in grCharNames:
print(fr' \def\Up{grCharName}{{{{{grLcUpDict[grCharName]}}}}}')
for grCharName in grCharNames:
print(fr' \def\Up{grCharName.title()}{{{{{grUcUpDict[grCharName]}}}}}')
print('$')
which produces the TeX macros for a Markdown cell:
$
\def\Upalpha{{\unicode{945}}}
\def\Upbeta{{\unicode{946}}}
\def\Upgamma{{\unicode{947}}}
\def\Updelta{{\unicode{948}}}
\def\Upepsilon{{\unicode{949}}}
\def\Upzeta{{\unicode{950}}}
\def\Upeta{{\unicode{951}}}
\def\Uptheta{{\unicode{952}}}
\def\Upiota{{\unicode{953}}}
\def\Upkappa{{\unicode{954}}}
\def\Uplambda{{\unicode{955}}}
\def\Upmu{{\unicode{956}}}
\def\Upnu{{\unicode{957}}}
\def\Upxi{{\unicode{958}}}
\def\Upomicron{{\unicode{959}}}
\def\Uppi{{\unicode{960}}}
\def\Uprho{{\unicode{961}}}
\def\Upsigma{{\unicode{963}}}
\def\Uptau{{\unicode{964}}}
\def\Upupsilon{{\unicode{965}}}
\def\Upphi{{\unicode{966}}}
\def\Upchi{{\unicode{967}}}
\def\Uppsi{{\unicode{968}}}
\def\Upomega{{\unicode{969}}}
\def\UpAlpha{{\unicode{913}}}
\def\UpBeta{{\unicode{914}}}
\def\UpGamma{{\unicode{915}}}
\def\UpDelta{{\unicode{916}}}
\def\UpEpsilon{{\unicode{917}}}
\def\UpZeta{{\unicode{918}}}
\def\UpEta{{\unicode{919}}}
\def\UpTheta{{\unicode{920}}}
\def\UpIota{{\unicode{921}}}
\def\UpKappa{{\unicode{922}}}
\def\UpLambda{{\unicode{923}}}
\def\UpMu{{\unicode{924}}}
\def\UpNu{{\unicode{925}}}
\def\UpXi{{\unicode{926}}}
\def\UpOmicron{{\unicode{927}}}
\def\UpPi{{\unicode{928}}}
\def\UpRho{{\unicode{929}}}
\def\UpSigma{{\unicode{931}}}
\def\UpTau{{\unicode{932}}}
\def\UpUpsilon{{\unicode{933}}}
\def\UpPhi{{\unicode{934}}}
\def\UpChi{{\unicode{935}}}
\def\UpPsi{{\unicode{936}}}
\def\UpOmega{{\unicode{937}}}
$
For clarity & test, in another cell, this will list the defined macro names and display the upper and lower case alphabets
grLcAlphabetMathJax = [fr'\Up{grCharName}' for grCharName in grCharNames]
grUcAlphabetMathJax = [fr'\Up{grCharName.title()}' for grCharName in grCharNames]
display(grLcAlphabetMathJax)
display(grUcAlphabetMathJax)
display(Math(''.join(grLcAlphabetMathJax)))
display(Math(''.join(grUcAlphabetMathJax)))
Thereby effectively reproducing Upgreek; skipping the lists its output is:
αβγδεζηθικλμνξοπρστυφχψω
ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ
Superseded Original
Workaround: referring to this excellent MathJax/TeX documentation we find the \unicode instruction for MathJax, and via this site the codes for an upright Pi symbol (as example).
This then allows the following in a notebook cell, after from IPython.display import display, HTML, Math, Latex
display(Math(r'\unicode[Segoe UI]{x03C0}'))
which generates π
whereas
display(Math(r'\unicode[familySTIXMathJax_Normal-italic]{x03C0}'))
generates an italicised 𝜋 (that attempting to switch to familySTIXMathJax_Normal does not seem to affect!?)
and ordinary display(Math(r'\pi')) generates 𝜋
Related
How to search for and highlight a substring in Codemirror 6?
I'm building a simple code editor to help children learn HTML. One feature I'm trying to add is that when users mouseover their rendered code (in an iframe), the corresponding HTML code in the editor is highlighted. So, for example, if a user mouses-over an image of kittens, the actual code, , would be highlighted in the editor. Mousing-over the iframe to get the html source for that element is the easy part, which I've done (using document.elementFromPoint(e.clientX, e.clientY in the iframe itself, and posting that up to the parent) - so that's not the part I need help with. The part I can't figure out is how to search for and highlight that string of selected code in the code editor. I'm using Codemirror 6 for this project, as it seems as it will give me the most flexibility to create such a feature. However, as a Codemirror 6 novice, I'm struggling with the documentation to find out where I should start. It seems like the steps I need to complete to accomplish this are: Search for a range in the editor's text that matches a string (ie.'<img src="kittens.gif"'). Highlight that range in the editor. Can anyone out there give me some advice as to where in the Codemirror 6 API I should look to start implementing this? It seems like it should be easy, but my unfamiliarity with the Codemirror API and the terse documentation is making this difficult.
1. Search for a range in the editor's text that matches a string (ie.'<img src="kittens.gif"'). You can use SearchCursor class (iterator) to get the character's range where is located the DOM element in your editor. // the import for SearchCursor class import {SearchCursor} from "#codemirror/search" // your editor's view let main_view = new EditorView({ /* your code */ }); // will create a cursor based on the doc content and the DOM element as a string (outerHTML) let cursor = new SearchCursor(main_view.state.doc, element.outerHTML); // will search the first match of the string element.outerHTML in the editor view main_view.state.doc cursor.next() // display the range where is located your DOM element in your editor console.log(cursor.value); 2. Highlight that range in the editor. As described in the migration documentation here, marked text is replace by decoration. To highlight a range in the editor with codemirror 6, you need to create one decoration and apply it in a dispatch on your view. This decoration need to be provide by an extension that you add in the extensions of your editor view. // the import for the 3 new classes import {StateEffect, StateField} from "#codemirror/state" import {Decoration} from "#codemirror/view" // code mirror effect that you will use to define the effect you want (the decoration) const highlight_effect = StateEffect.define(); // define a new field that will be attached to your view state as an extension, update will be called at each editor's change const highlight_extension = StateField.define({ create() { return Decoration.none }, update(value, transaction) { value = value.map(transaction.changes) for (let effect of transaction.effects) { if (effect.is(highlight_effect)) value = value.update({add: effect.value, sort: true}) } return value }, provide: f => EditorView.decorations.from(f) }); // this is your decoration where you can define the change you want : a css class or directly css attributes const highlight_decoration = Decoration.mark({ // attributes: {style: "background-color: red"} class: 'red_back' }); // your editor's view let main_view = new EditorView({ extensions: [highlight_extension] }); // this is where the change takes effect by the dispatch. The of method instanciate the effect. You need to put this code where you want the change to take place main_view.dispatch({ effects: highlight_effect.of([highlight_decoration.range(cursor.value.from, cursor.value.to)]) }); Hope it will help you to implement what you want ;)
Have a look at #codemirror/search. Specifically, the source code implementation of Selection Matching may be of use for you to adapt. It uses Decoration.mark over a range of text. You can use SearchCursor to iterate over ranges that match your pattern (or RegExpCursor)
Use getSearchCursor, something like this: var cursor = cmEditor.getSearchCursor(keyword , CodeMirror.Pos(cmEditor.firstLine(), 0), {caseFold: true, multiline: true}); if(cursor.find(false)){ //move to that position. cmEditor.setSelection(cursor.from(), cursor.to()); cmEditor.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20); } Programmatically search and select a keyword Take a look at getSearchCursor source code it it give some glow about how it works and its usage. So use getSearchCursor for finding text and optionally use markText for highlighting text because you can mark text with setSelection method of editor. Selection Marking Demo var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, styleSelectedText: true }); editor.markText({line: 6, ch: 26}, {line: 6, ch: 42}, {className: "styled-background"}); And it seem this is what you are looking for: codemirror: search and highlight multipule words without dialog RegExpCursor is another option that you can use: new RegExpCursor( text: Text, query: string, options?: {ignoreCase?: boolean}, from?: number = 0, to?: number = text.length ) Sample usage at: Replacing text between dollar signs for Mathml expression.
In Sublime Text, how can I replace a character with its Unicode?
In Sublime Text, how can I replace a character with its Unicode? For example, I want to replace 中 with 4E2D (or \u4E2D or something similar).
Sublime Text can be extended through Python plugins: Sublime comes with functionality that generates a skeleton of Python code needed to write a simple plugin. Select Tools | Developer | New Plugin... in the menu. Replace its content with the following code snippet: import sublime import sublime_plugin class SwapuniCommand(sublime_plugin.TextCommand): def run( self, edit): for region in self.view.sel(): if not region.empty(): # Get the selected text s = self.view.substr(region) # Transform it x = s.encode('raw_unicode_escape').decode() if x == s: x = s.encode('raw_unicode_escape').decode('unicode_escape') # Replace the selection with transformed text self.view.replace(edit, region, x) Save to Packages/User/swapuni.py. You can run it via entering view.run_command('swapuni') in the Sublime Text console (accessible via Ctrl+~), or by the following sublime-keymap (use your own keyboard shortcut in Preferences | Key Bindings): [ { "keys": ["ctrl+alt+r"], "command": "swapuni" } ]
Jupyter center only print output
How can I make a print output (but not other outputs like plots etc.) centered? For example this code: print("I want this text centered")
If you don't mind using HTML, then you can center text as follows: from IPython.core.display import display, HTML content = "Hello World" display(HTML(f"<div style='text-align:center'>{content}</div>")) Which will produce the following: You can also create a re-useable function that can be used instead of print: def centered(content): display(HTML(f"<div style='text-align:center'>{content}</div>")) Which would be used as follows: centered("My centered text.") And produces:
<h1><center>Centered text!</center></h1>
How did NPM create the border for their update message?
I'm assuming they used unicode characters to render the yellow box around the update message. What characters were used and does it look the same on all platforms?
How did NPM create the border for their update message? NPM uses npmlog to print to the console, and npmlog utilizes console-control-strings & gauge. console-control-strings mostly offers convenience functions for moving the cursor around the line and coloring the text. gauge provides the progress bar and spinner and a way to style them. What characters were used and does it look the same on all platforms? Unicode box-drawing characters are used for the border characters. I didn't research the exact unicode characters that NPM uses. Assuming that the terminal/platform is implemented to support unicode and, doesn't override the standard charset with its own characters (ie. emojis), I don't see why it wouldn't look the same across platform. The below snippet unicode characters don't match exactly. Instead, it demonstrates how to use control-control-strings to print something close to what NPM outputs. I'm sure with enough tinkering you could get it to be exact. const control = require('console-control-strings') let title = `${control.color('cyan')}Update available 5.0.3 \u2192 5.0.4${control.color('reset')}` let subtitle = `Run ${control.color('cyan')} npm i -g npm ${control.color('reset')}` let borderWidth = (title.length > subtitle.length ? title.length : subtitle.length) let topLeftCorner = '\u256D' let topRightCorner = '\u256E' let btmRightCorner = '\u256F' let btmLeftCorner = '\u2570' let border = [...Array(borderWidth)].map(() => { return '\u2500' }).join('') let topBorder = `${control.nextLine()}${control.color('yellow')}${topLeftCorner}${border}${topRightCorner}${control.color('reset')}` let btmBorder = `${control.nextLine()}${control.color('yellow')}${btmLeftCorner}${border}${btmRightCorner}${control.color('reset')}` let lineWrapper = `${control.color('yellow')}\u2502${control.color('reset')}` console.log(topBorder) console.log(`${lineWrapper}${control.forward(borderWidth)}${lineWrapper}`) console.log(`${control.nextLine()}${lineWrapper}${control.forward(4)}${title}${control.forward(5)}${lineWrapper}`) console.log(`${lineWrapper}${control.forward(11)}${subtitle}${control.forward(10)}${lineWrapper}`) console.log(`${lineWrapper}${control.forward(borderWidth)}${lineWrapper}`) console.log(`${btmBorder}${control.color('reset')}`)
How to automatically color lines in IDA?
I want IDA to automatically color lines in both the graph and text view for important instructions, for example wherever there is a call or xor instruction change the background color of each of those references to a certain color. Here is what I am looking to achieve: fig.1 graph view fig.2 text view I noticed you can go to Edit > Other > color instruction... from the main menu and this will allow you to change the background color of the selected instruction, but this does not change all of them and seems to only affect the current database. How can I make IDA automatically color certain instructions such as call and xoras shown from the example images? I want it to automatically work for any database I open.
You need to write an IDA plug in using IDAPython (python for IDA) or IDC (IDA scripting language which is very similar to C), the following code is in IDC: #include <idc.idc> static main(void) { auto currentEA; auto currentMnem; auto prevMnem; auto currentOp; prevMnem = ""; currentOp; currentEA = FirstSeg(); currentEA = NextHead(currentEA, 0xFFFFFFFF); while (currentEA != BADADDR) { currentMnem = GetMnem(currentEA); //Highlight call functions if (currentMnem == "call") { SetColor(currentEA, CIC_ITEM, 0xc7c7ff); } } } You can also refer to the opcodes' operands: //Non-zeroing XORs are often signs of data encoding if (currentMnem == "xor") { if (GetOpnd(currentEA, 0) != GetOpnd(currentEA, 1)) { SetColor(currentEA, CIC_ITEM, 0xFFFF00); } } Here is a guide from Hex Blog for using IDC plug-ins. And here is a sample for similar script in IDA Python instead of IDC.