## Popular New Releases in Latex

KaTeX

v0.15.3

penrose

v1.3.0

handcalcs

handcalcs v1.4.0

bookdown

bookdown 0.26

arxiv-latex-cleaner

Release v0.1.25

## Popular Libraries in Latex

by KaTeX javascript

15047 MIT

Fast math typesetting for the web.

by gollum ruby

12377 MIT

A simple, Git-powered wiki with a sweet API and local frontend.

by RelaxedJS javascript

11616 ISC

Create PDF documents using web technologies

by pandao javascript

11266 MIT

The open source embeddable online markdown editor (component).

by overleaf javascript

9317 AGPL-3.0

A web-based collaborative LaTeX editor

by James-Yu typescript

8290 MIT

Boost LaTeX typesetting efficiency with preview, compile, autocomplete, colorize, and more.

by ikatyang javascript

6948 MIT

A markdown version emoji cheat sheet

by penrose typescript

5350 MIT

Create beautiful diagrams just by typing mathematical notation in plain text.

by edwardtufte html

4923 MIT

Style your webpage like Edward Tufte’s handouts.

## Trending New libraries in Latex

by connorferster css

3266 Apache-2.0

Python library for converting Python calculations into rendered latex.

by vincentdoerig html

2249 MIT

LaTeX.css is a CSS library that makes your website look like a LaTeX document

by Hedgehog-Computing typescript

1898 Apache-2.0

Run, compile and execute JavaScript for Scientific Computing and Data Visualization TOTALLY TOTALLY TOTALLY in your BROWSER! An open source scientific computing environment for JavaScript TOTALLY in your browser, matrix operations with GPU acceleration, TeX support, data visualization and symbolic computation.

by google python

1747 Apache-2.0

Generates LaTeX math description from Python functions.

by lukas-blecher python

1255 MIT

pix2tex: Using a ViT to convert images of equations into LaTeX code.

by h-enk html

918 MIT

Hugo theme helping you build modern documentation websites.

by kingyiusuen python

671 MIT

Convert images of LaTex math equations into LaTex code.

by susam javascript

508 MIT

Self-rendering and distributable mathematics chalkboards

by MarkMindLtd javascript

461 MIT

MarkMind — a mind map and outliner editor for Windows, Mac, Linux, andriod and ios ,it support markdown in node.

## Top Authors in Latex

1

11 Libraries

69

2

9 Libraries

2602

3

8 Libraries

240

4

7 Libraries

2308

5

6 Libraries

56

6

6 Libraries

2559

7

5 Libraries

774

8

5 Libraries

62

9

5 Libraries

6508

10

5 Libraries

518

1

11 Libraries

69

2

9 Libraries

2602

3

8 Libraries

240

4

7 Libraries

2308

5

6 Libraries

56

6

6 Libraries

2559

7

5 Libraries

774

8

5 Libraries

62

9

5 Libraries

6508

10

5 Libraries

518

## Trending Kits in Latex

* No Trending Kits are available at this moment for Latex*

## Trending Discussions on Latex

Textmate latex compilation : pb with python version after macOS update Monterey 12.3

Latex math text in PIL ImageDraw text()

Kth smallest number algorithm doing extra work?

biber wants to load libcrypt.so.1 but it is missing

LaTeX in plot titles using a loop

Is there a way to resolve repeated server error problem in LaTex (Overleaf)?

How do I type accented characters in ASCII-encoded Rd files?

Implementation of the Metropolis-Hasting algorithm for solving gaussian integrals

Linearize nested for loops

Scientific formats, subscripts and superscripts in RMarkdown table (docx output)

QUESTION

Textmate latex compilation : pb with python version after macOS update Monterey 12.3

Asked 2022-Mar-22 at 10:19I use textmate for make pdf file in latex. After the update of macOS Monterey version 12.3, the minimal version of python (/usr/bin/python) has disappeared : the compilation don't work now. I try to change in the textmate's files /usr/bin/python by /usr/bin/python3 (I have only this python folder) but that always don't work.

the error say me ti change the compilation command which is this :

```
1 #!/usr/bin/env ruby18
2# coding: utf-8
3
4require ENV["TM_SUPPORT_PATH"] + "/lib/tm/process"
5require ENV["TM_SUPPORT_PATH"] + "/lib/tm/htmloutput"
6require ENV["TM_SUPPORT_PATH"] + "/lib/tm/save_current_document"
7
8# To enable the typesetting of unsaved documents, you must change the “Save” setting of
9# this command to “Current File” and add the variable TM_LATEX_AUTOSAVE to TextMate's
10# Shell Variables preferences. Be warned that your document must be encoded as UTF-8 if
11# you exercise this option — becauseTextMate.save_current_document cannot know the file
12# encoding you prefer.
13
14TextMate.save_current_document unless ENV["TM_LATEX_AUTOSAVE"].nil?
15
16texmate = ENV["TM_BUNDLE_SUPPORT"] + "/bin/texmate.py"
17engine_version = TextMate::Process.run(texmate, "version")
18TextMate::HTMLOutput.show(:title => "Typesetting “#{ENV["TM_DISPLAYNAME"] || File.basename(ENV["TM_FILEPATH"])}”…", :sub_title => engine_version) do |io|
19 TextMate::Process.run(texmate, 'latex', :interactive_input => false) do |line|
20 io << line
21 end
22end
23::Process.exit($?.exitstatus || 0) # exitstatus is nil if our process is prematurely terminated (SIGINT)
24
```

Thank you very much for your help. PS : The compilation work with texshop, I don't think it is a latex problem

ANSWER

Answered 2022-Mar-18 at 07:00I just found the following page: https://www.heise.de/news/macOS-12-3-Apple-wirft-Python-raus-6341999.html which told me that Apple does not support Python (and some other script languages like for instance Perl) any further. The last version they supported was Python 2.7. Developers should install (and care for) Python 3 by themselves. The Python page told exactly the same thing:

QUESTION

Latex math text in PIL ImageDraw text()

Asked 2022-Mar-10 at 06:08I'm trying to annotate a few figures I created in python. So, I'm generating an image containing the specified text (using PIL ImageDraw) and concatenating it with the image. Now, I want to include a math notation into the text. Is there a way to write text in latex math when creating the image of text? This answer suggests a work-around by using unicode text, but I would prefer writing the text in latex directly.

MWE:

```
1from PIL import ImageFont, Image, ImageDraw
2from matplotlib import pyplot
3
4
5def get_annotation(image_shape: tuple, title: str, font_size: int = 50):
6 frame_height, frame_width = image_shape[:2]
7 times_font = ImageFont.truetype('times-new-roman.ttf', font_size)
8 text_image = Image.new('RGB', (frame_width, frame_height), (255, 255, 255))
9 drawer = ImageDraw.Draw(text_image)
10 w, h = drawer.textsize(title, font=times_font)
11 drawer.text(((frame_width - w) / 2, (frame_height - h) / 2), text=title, fill=(0, 0, 0), font=times_font,
12 align='center')
13 annotation = numpy.array(text_image)
14 return annotation
15
16if __name__ == '__main__':
17 anno = get_annotation((100, 300), 'frame $f_n$')
18 pyplot.imshow(anno)
19 pyplot.show()
20
```

I tried passing `frame $f_n$`

to `title`

parameter, but dollars got printed in the text image.

PS: times-new-roman.ttf can be obtained here

ANSWER

Answered 2022-Mar-10 at 06:08I found an alternative with sympy here

```
1from PIL import ImageFont, Image, ImageDraw
2from matplotlib import pyplot
3
4
5def get_annotation(image_shape: tuple, title: str, font_size: int = 50):
6 frame_height, frame_width = image_shape[:2]
7 times_font = ImageFont.truetype('times-new-roman.ttf', font_size)
8 text_image = Image.new('RGB', (frame_width, frame_height), (255, 255, 255))
9 drawer = ImageDraw.Draw(text_image)
10 w, h = drawer.textsize(title, font=times_font)
11 drawer.text(((frame_width - w) / 2, (frame_height - h) / 2), text=title, fill=(0, 0, 0), font=times_font,
12 align='center')
13 annotation = numpy.array(text_image)
14 return annotation
15
16if __name__ == '__main__':
17 anno = get_annotation((100, 300), 'frame $f_n$')
18 pyplot.imshow(anno)
19 pyplot.show()
20import sympy
21
22sympy.preview(r'frame $f_n$', dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600"], viewer='file', filename='test.png', euler=False)
23
```

QUESTION

Kth smallest number algorithm doing extra work?

Asked 2022-Feb-27 at 08:40So I'm preparing for a technical interview, and one of my practice questions is the Kth smallest number. I know that I can do a sort for O(n * log(n)) time and use a heap for O(n * log(k)). However I also know I can partition it (similar to quicksort) for an average case of O(n).

The actual calculated average time complexity should be:

I've double checked this math using WolframAlpha, and it agrees.

So I've coded my solution, and then I calculated the actual average time complexity on random data sets. For small values of n, it's pretty close. For example n=5 might give me an actual of around 6.2 when I expect around 5.7. This slightly more error is consistent.

This only gets worse as I increase the value of n. For example, for n=5000, I get around 15,000 for my actual average time complexity, when it should be slightly less than 10,000.

So basically, my question is where are these extra iterations coming from? Is my code wrong, or is it my math? My code is below:

```
1import java.util.Arrays;
2import java.util.Random;
3
4public class Solution {
5 static long tc = 0;
6
7 static void swap(int[] arr, int i, int j) {
8 int temp = arr[i];
9 arr[i] = arr[j];
10 arr[j] = temp;
11 }
12
13 static int kMin(int[] arr, int k) {
14 arr = arr.clone();
15 int pivot = pivot(arr);
16 if(pivot > k) {
17 return kMin(Arrays.copyOfRange(arr, 0, pivot), k);
18 } else if(pivot < k) {
19 return kMin(Arrays.copyOfRange(arr, pivot + 1, arr.length), k - pivot - 1);
20 }
21 return arr[k];
22 }
23
24 static int pivot(int[] arr) {
25 Random rand = new Random();
26 int pivot = rand.nextInt(arr.length);
27
28 swap(arr, pivot, arr.length - 1);
29
30 int i = 0;
31 for(int j = 0; j < arr.length - 1; j++) {
32 tc++;
33 if(arr[j] < arr[arr.length - 1]) {
34 swap(arr, i, j);
35 i++;
36 }
37 }
38 swap(arr, i, arr.length - 1);
39 return i;
40 }
41
42 public static void main(String args[]) {
43 int iterations = 10000;
44 int n = 5000;
45 for(int j = 0; j < iterations; j++) {
46 Random rd = new Random();
47 int[] arr = new int[n];
48 for (int i = 0; i < arr.length; i++) {
49 arr[i] = rd.nextInt();
50 }
51 int k = rd.nextInt(arr.length - 1);
52 kMin(arr, k);
53 }
54 System.out.println("Actual: " + tc / (double)iterations);
55
56 double expected = 2.0 * n - 2.0 - (Math.log(n) / Math.log(2));
57 System.out.println("Expected: " + expected);
58 }
59
60
61}
62
```

ANSWER

Answered 2022-Feb-27 at 08:40As you and others have pointed out in the comments, your calculation assumed that the array was split in half on each iteration by the random pivot, which is incorrect. This uneven splitting has a significant impact: when the element you're trying to select is the actual median, for instance, the expected size of the array after one random pivot choice is 75% of the original, since you'll always choose the larger of the two arrays.

For an accurate estimate of the expected comparisons for each value of `n`

and `k`

, David Eppstein published an accessible analysis here and derives this formula:

This is a very close estimate for your values, even though this assumes no duplicates in the array.

Calculating the expected number of comparisons for k from `1`

to `n-1`

, as you do, gives ** ~7.499 * 10^7** total comparisons when

`n=5000`

, or almost exactly **comparisons per call of Quickselect as you observed.**

`15,000`

QUESTION

biber wants to load libcrypt.so.1 but it is missing

Asked 2022-Feb-21 at 10:53I am Arch GNU/Linux user who usually manages almost every package with pacman; I manage TeX and LaTeX-related things with tlmgr. I installed tlmgr from source.

I am writing paper. I would like to use bibliography.

When I tried `latexmk -pdflua main.ltx`

:

```
1Rc files read:
2 latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6 'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16 biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19
```

`libcrypt.so*`

on my environment```
1Rc files read:
2 latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6 'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16 biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19$ pacman -Qo /usr/lib/libcrypt*
20/usr/lib/libcrypto.so is owned by openssl 1.1.1.m-1
21/usr/lib/libcrypto.so.1.1 is owned by openssl 1.1.1.m-1
22/usr/lib/libcryptsetup.so is owned by cryptsetup 2.4.3-2
23/usr/lib/libcryptsetup.so.12 is owned by cryptsetup 2.4.3-2
24/usr/lib/libcryptsetup.so.12.7.0 is owned by cryptsetup 2.4.3-2
25/usr/lib/libcrypt.so is owned by libxcrypt 4.4.28-1
26/usr/lib/libcrypt.so.2 is owned by libxcrypt 4.4.28-1
27/usr/lib/libcrypt.so.2.0.0 is owned by libxcrypt 4.4.28-1
28
```

**What I tried else**

I uninstalled and re-installed biber on tlmgr but did not work.

```
1Rc files read:
2 latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6 'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16 biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19$ pacman -Qo /usr/lib/libcrypt*
20/usr/lib/libcrypto.so is owned by openssl 1.1.1.m-1
21/usr/lib/libcrypto.so.1.1 is owned by openssl 1.1.1.m-1
22/usr/lib/libcryptsetup.so is owned by cryptsetup 2.4.3-2
23/usr/lib/libcryptsetup.so.12 is owned by cryptsetup 2.4.3-2
24/usr/lib/libcryptsetup.so.12.7.0 is owned by cryptsetup 2.4.3-2
25/usr/lib/libcrypt.so is owned by libxcrypt 4.4.28-1
26/usr/lib/libcrypt.so.2 is owned by libxcrypt 4.4.28-1
27/usr/lib/libcrypt.so.2.0.0 is owned by libxcrypt 4.4.28-1
28# ln -s /usr/lib/libcrypt.so /usr/lib/libcrypt.so.1
29$ latexmkrc -pdflua main.ltx
30Rc files read:
31 latexmkrc
32Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
33Latexmk: applying rule 'biber main'...
34Rule 'biber main': The following rules & subrules became out-of-date:
35 'biber main'
36------------
37Run number 1 of rule 'biber main'
38------------
39------------
40Running 'biber "main.bcf"'
41------------
42/tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber: /usr/lib/libcrypt.so.1: version `GLIBC_2.2.5' not found (required by /tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber)
43Latexmk: Errors, so I did not complete making targets
44Collected error summary (may duplicate other messages):
45 biber main: Could not open biber log file for 'main'
46Latexmk: Use the -f option to force complete processing,
47 unless error was exceeding maximum runs, or warnings treated as errors.
48
```

**File source**

latexmkrc:

```
1Rc files read:
2 latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6 'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16 biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19$ pacman -Qo /usr/lib/libcrypt*
20/usr/lib/libcrypto.so is owned by openssl 1.1.1.m-1
21/usr/lib/libcrypto.so.1.1 is owned by openssl 1.1.1.m-1
22/usr/lib/libcryptsetup.so is owned by cryptsetup 2.4.3-2
23/usr/lib/libcryptsetup.so.12 is owned by cryptsetup 2.4.3-2
24/usr/lib/libcryptsetup.so.12.7.0 is owned by cryptsetup 2.4.3-2
25/usr/lib/libcrypt.so is owned by libxcrypt 4.4.28-1
26/usr/lib/libcrypt.so.2 is owned by libxcrypt 4.4.28-1
27/usr/lib/libcrypt.so.2.0.0 is owned by libxcrypt 4.4.28-1
28# ln -s /usr/lib/libcrypt.so /usr/lib/libcrypt.so.1
29$ latexmkrc -pdflua main.ltx
30Rc files read:
31 latexmkrc
32Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
33Latexmk: applying rule 'biber main'...
34Rule 'biber main': The following rules & subrules became out-of-date:
35 'biber main'
36------------
37Run number 1 of rule 'biber main'
38------------
39------------
40Running 'biber "main.bcf"'
41------------
42/tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber: /usr/lib/libcrypt.so.1: version `GLIBC_2.2.5' not found (required by /tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber)
43Latexmk: Errors, so I did not complete making targets
44Collected error summary (may duplicate other messages):
45 biber main: Could not open biber log file for 'main'
46Latexmk: Use the -f option to force complete processing,
47 unless error was exceeding maximum runs, or warnings treated as errors.
48$latex='lualatex %O -synctex=1 -interaction=nonstopmode %S';
49#$bibtex='upbibtex %O %B';
50$bibtex='biber %O %B';
51$makeindex='upmendex %O -o %D %S';
52$pdf_mode=3;
53
```

ANSWER

Answered 2022-Feb-21 at 10:53Install `libxcrypt-compat`

from the AUR, as suggest in this answer.

This made my `biber`

from TeX Live 2020 work again. The interesting question is if newer TeX distributions will require this AUR package.

QUESTION

LaTeX in plot titles using a loop

Asked 2022-Feb-19 at 18:02I just learned how to insert (a limited number of) LaTeX expressions into my plot titles with
`expression(<LaTeX code>)`

. How can I generate plots containing LaTeX in their titles using a *loop*? For example, say I have:

```
1par(mfrow = c(2,2))
2
3x <- seq(1,10,0.1)
4y <- sin(x)
5
6plot(x, y, main = expression(sigma[1]))
7plot(x, y, main = expression(sigma[2]))
8
```

This produces the desired output:

How can I achieve the same output, but by replacing the last two lines with a loop? I tried

```
1par(mfrow = c(2,2))
2
3x <- seq(1,10,0.1)
4y <- sin(x)
5
6plot(x, y, main = expression(sigma[1]))
7plot(x, y, main = expression(sigma[2]))
8par(mfrow = c(2,2))
9for (i in 1:2){
10 plot(x, y, main = expression(sigma[i]))
11}
12
```

ANSWER

Answered 2022-Feb-19 at 17:04We can use `bquote`

instead of `expression`

. This allows partial unquoting, meaning you can substitute the *value* of *i* inside the expression by wrapping it like this: `.(i)`

```
1par(mfrow = c(2,2))
2
3x <- seq(1,10,0.1)
4y <- sin(x)
5
6plot(x, y, main = expression(sigma[1]))
7plot(x, y, main = expression(sigma[2]))
8par(mfrow = c(2,2))
9for (i in 1:2){
10 plot(x, y, main = expression(sigma[i]))
11}
12par(mfrow = c(2,2))
13
14x <- seq(1,10,0.1)
15y <- sin(x)
16
17for(i in 1:4) plot(x, y, main = bquote(paste("My plot for ", sigma[.(i)], " :")))
18
```

^{Created on 2022-02-19 by the reprex package (v2.0.1)}

QUESTION

Is there a way to resolve repeated server error problem in LaTex (Overleaf)?

Asked 2022-Feb-13 at 12:12I ran into this error while trying to compile my overleaf latex;

"Server Error Sorry, something went wrong and your project could not be compiled. Please try again in a few moments".

Your response will be helpful. Thanks

ANSWER

Answered 2022-Feb-13 at 08:47This problem may arise as a result of the internet connection. The simple way to resolve this problem is to reload the Overleaf editor by refreshing your browser.

QUESTION

How do I type accented characters in ASCII-encoded Rd files?

Asked 2022-Feb-08 at 13:38Can LaTeX escapes for accents be used in `Rd`

files? I tried the standard `\'e`

and many variants (`\'{e}`

, `{\'e}`

, `\\'e`

, `\\'{e}`

, `{\\'e}`

, etc.), but none is rendered as an accented character in the PDF or HTML output.

I want my References section (i.e. `\references{}`

) to be rendered with accented characters, but I do not want to type non-ASCII characters in my `Rd`

files. Is there good/recommended practice? Should I simply replace non-ASCII characters with their ASCII equivalents (é → e, ø → o)?

To be clear, I know it is possible to type accented characters (e.g., `é`

) directly in UTF-8-encoded files, but I would prefer to keep ASCII-encoded files.

This question is *not* about

- how to type special/accented letters in LaTeX
- how to use UTF-8 in LaTeX
- accents/special characters in R Markdown

or variants.

**Minimal test package**

Package structure

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7
```

`test/man/one.Rd`

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14
```

`test/R/one.R`

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one <- function() 1
15
```

`test/DESCRIPTION`

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one <- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody <no@body.org>
20Description: Test.
21License: GPL-3
22
```

Build, check, and install with:

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one <- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody <no@body.org>
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25
```

ANSWER

Answered 2022-Feb-07 at 16:21Using math mode it works. Not sure 100% if this is what you are looking for.

Here are some examples:

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one <- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody <no@body.org>
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25 \'{e} {\'e} \\'e \\'{e} {\\'e}
26
27$\acute{e}$
28
29$\grave{e}$
30
31$\tilde{e}$
32
33
```

PDF output:

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one <- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody <no@body.org>
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25 \'{e} {\'e} \\'e \\'{e} {\\'e}
26
27$\acute{e}$
28
29$\grave{e}$
30
31$\tilde{e}$
32
33’{e} {’e} \‘e \’{e} {\’e}
34é
35è
36ẽ
37
```

Update:

```
1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one <- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody <no@body.org>
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25 \'{e} {\'e} \\'e \\'{e} {\\'e}
26
27$\acute{e}$
28
29$\grave{e}$
30
31$\tilde{e}$
32
33’{e} {’e} \‘e \’{e} {\’e}
34é
35è
36ẽ
37\newcommand\latexcode[1]{#1}
38
39\latexcode{\'{a}}
40
41Thoma\latexcode{\'{s}}
42
```

That works Thomas !

QUESTION

Implementation of the Metropolis-Hasting algorithm for solving gaussian integrals

Asked 2022-Feb-02 at 20:28I am currently having issue with the implementation of the Metropolis-Hastings algorithm.

I am trying to use the algorithm to calculate integrals of the form

In using this algorithm, we can obtain a long chain of configurations ( in this case, each configuration is just a single numbers) such that in the tail-end of the chain the probability of having a particular configuration follows (or rather tends to) a gaussian distribution.

My code seems to be messing up with obtaining the said gaussian distributions. There is a strange dependence on the transition probablity (the probablity of picking a new candidate configuration depending on the previous configuration in the chain). However, if this transition probability is symmetric, there should be no dependence on this function at all (it only affects speed at which phase space [space of potential configurations] is explored and how quickly the chain converges to the desired distribution)!

In my case I am using a normal distribution transition function (which satisfies the need to be symmetric), with width d. For each d I use I do indeed get a gaussian distribution however the standard deviation, sigma, depends on my choice of d. The resulting gaussian should have a sigma of roughly 0.701 but I find that the value I actually get depends on the parameter d, when it shouldn't.

I am not sure where the error in this code is, any help would be greatly appreciated!

```
1import numpy as np
2import matplotlib.pyplot as plt
3from scipy.stats import norm
4
5
6'''
7We want to get an exponential decay integral approx using importance sampling.
8We will try to integrate x^2exp(-x^2) over the real line.
9Metropolis-hasting alg will generate configuartions (in this case, single numbers) such that
10the probablity of a given configuration x^a ~ p(x^a) for p(x) propto exp(-x^2).
11
12Once configs = {x^a} generated, the apporximation, Q_N, of the integral, I, will be given by
13Q_N = 1/N sum_(configs) x^2
14lim (N-> inf) Q_N -> I
15'''
16
17'''
18Implementing metropolis-hasting algorithm
19'''
20
21#Setting up the initial config for our chain, generating first 2 to generate numpy array
22x_0 = np.random.uniform(-20,-10,2)
23
24#Defining function that generates the next N steps in the chain, given a starting config x
25#Works by iteratively taking the last element in the chain, generating a new candidate configuration from it and accepting/rejecting according to the algorithm
26#Success and failures implemented to see roughly the success rate of each step
27def next_steps(x,N):
28 i = 0
29 Success = 0
30 Failures = 0
31 Data = np.array(x)
32 d = 1.5 #Spread of (normal) transition function
33 while i < N:
34 r = np.random.uniform(0,1)
35 delta = np.random.normal(0,d)
36 x_old = Data[-1]
37 x_new = x_old + delta
38 hasting_ratio = np.exp(-(x_new**2-x_old**2) )
39 if hasting_ratio > r:
40 i = i+1
41 Data = np.append(Data,x_new)
42 Success = Success +1
43 else:
44 Failures = Failures + 1
45 print(Success)
46 print(Failures)
47 return Data
48
49#Number of steps in the chain
50N_iteration = 50000
51
52#Generating the data
53Data = next_steps(x_0,N_iteration)
54
55#Plotting data to see convergence of chain to gaussian distribution
56plt.plot(Data)
57plt.show()
58
59#Obtaining tail end data and obtaining the standard deviation of resulting gaussian distribution
60Data = Data[-40000:]
61(mu, sigma) = norm.fit(Data)
62print(sigma)
63
64
65#Plotting a histogram to visually see if guassian
66plt.hist(Data, bins = 300)
67plt.show()
68
```

ANSWER

Answered 2022-Feb-02 at 20:28You need to save x even when it doesn't change. Otherwise the center values are under-counted, and more so as `d`

increases, which increases the variance.

```
1import numpy as np
2import matplotlib.pyplot as plt
3from scipy.stats import norm
4
5
6'''
7We want to get an exponential decay integral approx using importance sampling.
8We will try to integrate x^2exp(-x^2) over the real line.
9Metropolis-hasting alg will generate configuartions (in this case, single numbers) such that
10the probablity of a given configuration x^a ~ p(x^a) for p(x) propto exp(-x^2).
11
12Once configs = {x^a} generated, the apporximation, Q_N, of the integral, I, will be given by
13Q_N = 1/N sum_(configs) x^2
14lim (N-> inf) Q_N -> I
15'''
16
17'''
18Implementing metropolis-hasting algorithm
19'''
20
21#Setting up the initial config for our chain, generating first 2 to generate numpy array
22x_0 = np.random.uniform(-20,-10,2)
23
24#Defining function that generates the next N steps in the chain, given a starting config x
25#Works by iteratively taking the last element in the chain, generating a new candidate configuration from it and accepting/rejecting according to the algorithm
26#Success and failures implemented to see roughly the success rate of each step
27def next_steps(x,N):
28 i = 0
29 Success = 0
30 Failures = 0
31 Data = np.array(x)
32 d = 1.5 #Spread of (normal) transition function
33 while i < N:
34 r = np.random.uniform(0,1)
35 delta = np.random.normal(0,d)
36 x_old = Data[-1]
37 x_new = x_old + delta
38 hasting_ratio = np.exp(-(x_new**2-x_old**2) )
39 if hasting_ratio > r:
40 i = i+1
41 Data = np.append(Data,x_new)
42 Success = Success +1
43 else:
44 Failures = Failures + 1
45 print(Success)
46 print(Failures)
47 return Data
48
49#Number of steps in the chain
50N_iteration = 50000
51
52#Generating the data
53Data = next_steps(x_0,N_iteration)
54
55#Plotting data to see convergence of chain to gaussian distribution
56plt.plot(Data)
57plt.show()
58
59#Obtaining tail end data and obtaining the standard deviation of resulting gaussian distribution
60Data = Data[-40000:]
61(mu, sigma) = norm.fit(Data)
62print(sigma)
63
64
65#Plotting a histogram to visually see if guassian
66plt.hist(Data, bins = 300)
67plt.show()
68import numpy as np
69from scipy.stats import norm
70
71
72"""
73We want to get an exponential decay integral approx using importance sampling.
74We will try to integrate x^2exp(-x^2) over the real line.
75Metropolis-hasting alg will generate configuartions (in this case, single numbers) such that
76the probablity of a given configuration x^a ~ p(x^a) for p(x) propto exp(-x^2).
77
78Once configs = {x^a} generated, the apporximation, Q_N, of the integral, I, will be given by
79Q_N = 1/N sum_(configs) x^2
80lim (N-> inf) Q_N -> I
81"""
82
83"""
84Implementing metropolis-hasting algorithm
85"""
86
87# Setting up the initial config for our chain
88x_0 = np.random.uniform(-20, -10)
89
90# Defining function that generates the next N steps in the chain, given a starting config x
91# Works by iteratively taking the last element in the chain, generating a new candidate configuration from it and accepting/rejecting according to the algorithm
92# Success and failures implemented to see roughly the success rate of each step
93def next_steps(x, N):
94 Success = 0
95 Failures = 0
96 Data = np.empty((N,))
97 d = 1.5 # Spread of (normal) transition function
98 for i in range(N):
99 r = np.random.uniform(0, 1)
100 delta = np.random.normal(0, d)
101 x_new = x + delta
102 hasting_ratio = np.exp(-(x_new ** 2 - x ** 2))
103 if hasting_ratio > r:
104 x = x_new
105 Success = Success + 1
106 else:
107 Failures = Failures + 1
108 Data[i] = x
109 print(Success)
110 print(Failures)
111 return Data
112
113
114# Number of steps in the chain
115N_iteration = 50000
116
117# Generating the data
118Data = next_steps(x_0, N_iteration)
119
120# Obtaining tail end data and obtaining the standard deviation of resulting gaussian distribution
121Data = Data[-40000:]
122(mu, sigma) = norm.fit(Data)
123print(sigma)
124
```

QUESTION

Linearize nested for loops

Asked 2022-Feb-01 at 08:27I'm working on some heavy algorithm, and now I'm trying to make it multithreaded. It has a loop with 2 nested loops:

```
1for (int i = 0; i < n; ++i) {
2 for (int j = i + 1; j < n; ++j) {
3 for (int k = j + 1; k < n; ++k) {
4 function(i, j, k);
5 }
6 }
7}
8
```

I know, that the number of `function`

calls will be equal to

But I have one last problem: I don't know how to calculate `i`

, `j`

and `k`

based on `b`

(`0 <= b < binom(n, 3)`

)

```
1for (int i = 0; i < n; ++i) {
2 for (int j = i + 1; j < n; ++j) {
3 for (int k = j + 1; k < n; ++k) {
4 function(i, j, k);
5 }
6 }
7}
8for (int b = start; b < end; ++b) {
9 // how to calculate i, j, k?
10}
11
```

How can I calculate these values?

**EDIT**:
My main idea is to call function like this from different threads:

```
1for (int i = 0; i < n; ++i) {
2 for (int j = i + 1; j < n; ++j) {
3 for (int k = j + 1; k < n; ++k) {
4 function(i, j, k);
5 }
6 }
7}
8for (int b = start; b < end; ++b) {
9 // how to calculate i, j, k?
10}
11void calculate(int start, int end) {
12 for (int b = start; b < end; ++b) {
13 int i = ...;
14 int j = ...;
15 int k = ...;
16 function(i, j, k);
17 }
18}
19
20int total = binom(n, 3);
21
22// thread A:
23calculate(0, total / 2);
24
25// thread B:
26calculate(total / 2, total);
27
```

ANSWER

Answered 2021-Dec-20 at 09:25A third attempt:

I've taken your code, and at last got it to run properly (in python):

```
1for (int i = 0; i < n; ++i) {
2 for (int j = i + 1; j < n; ++j) {
3 for (int k = j + 1; k < n; ++k) {
4 function(i, j, k);
5 }
6 }
7}
8for (int b = start; b < end; ++b) {
9 // how to calculate i, j, k?
10}
11void calculate(int start, int end) {
12 for (int b = start; b < end; ++b) {
13 int i = ...;
14 int j = ...;
15 int k = ...;
16 function(i, j, k);
17 }
18}
19
20int total = binom(n, 3);
21
22// thread A:
23calculate(0, total / 2);
24
25// thread B:
26calculate(total / 2, total);
27def get_k(n):
28 total = 0
29 for i in range(3, n):
30 for j in range(i + 1, n):
31 for k in range(j + 1, n):
32 total += 1
33
34 V = total // 2 # for 2 threads
35 V_tmp = 0
36 for i in range(3, n):
37 if(V_tmp > V):
38 return i
39 for j in range(i + 1, n):
40 for k in range(j + 1, n):
41 V_tmp += 1
42
43def pseudo_thread(start, end, n):
44 counter = 0
45
46 for i in range(start, end):
47 for j in range(i + 1, n):
48 for k in range(j + 1, n):
49 counter += 1
50 print(counter)
51
52
53n = 145
54k = get_k(n)
55
56pseudo_thread(3, k, n)
57pseudo_thread(k, n, n)
58
```

This should finally give you a relatively good split. Even with n=145, we get 239260 and 227920 for our counter values. It's obviously not an elegant solution, and also not perfect, but it gives you the right answer without much reference to detailed mathematics.

QUESTION

Scientific formats, subscripts and superscripts in RMarkdown table (docx output)

Asked 2022-Jan-31 at 22:52Let's say I have the following rmd:

```
1---
2title: "Table won't work"
3author: "Exhausted student"
4date: "2022/01/28"
5output:
6 bookdown::word_document2
7---
8
9```{r table, echo=F, warning=F, message=F}
10library(tidyverse)
11a <- tibble(
12 constants = c("c", "NA", "h", "e", "H2O"),
13 values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
14)
15
16knitr::kable(a, digits = 35)
17```
18
```

which produces this table in Word.

**The Problem**

I need the scientific format to use superscripts and multiply sign (i.e. 2.998 × 10^{8}), and some cells requires subscript (e.g. N_{A} and H_{2}O).

The final table should look like this. How can I do that?

**What I've tried/would never try**

: I managed to format some contents as`huxtable`

package and its`markdown()`

function`H~2~O`

, then enable markdown across table by`huxtable(a) %>% `markdown<-`(TRUE)`

. Which did not recognize the syntax, and apparently would not work in forseeable future according to the author.: Produces right format. I pass the lables to`flextable`

and`as_sub()`

`flextable::compose()`

, where the labels were something like`as_paragraph(list_values = list("H", as_sub("2"), "O")`

. The code is obviously too lengthy; plus i have to**manipulate cells one-by-one**. Technically still doable, but I do have tables with 100+ cells needed formatting.**Output first, format in Word later**: Again, needed manipulation one-by-one. Would be an option if it would work everything out**automatically**.- Convincing the school bureaucrats to accept
**html/pdf/latex as output**: this is forever an impossible option. - Format outside word then
**export formatted table as image**: strictly forbidden in the reports.

**Edit:** the table works now! Great thanks to Maël's answer, but please check my own findings to see my final result:

ANSWER

Answered 2022-Jan-31 at 22:52Your code should look like this:

```
1---
2title: "Table won't work"
3author: "Exhausted student"
4date: "2022/01/28"
5output:
6 bookdown::word_document2
7---
8
9```{r table, echo=F, warning=F, message=F}
10library(tidyverse)
11a <- tibble(
12 constants = c("c", "NA", "h", "e", "H2O"),
13 values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
14)
15
16knitr::kable(a, digits = 35)
17```
18```
19{r table, echo=F, warning=F, message=F}
20library(tidyverse)
21a <- tibble(
22 constants = c("c", "NA", "h", "e", "$H_2O$"),
23 values = c("$2.998 * {10^{8}}$", "$6.022 * {10^{-23}}$", "$6.626 * {10^{-34}}$", "$-1.602 * {10 ^{-19}}$", "$1.802 * {10^{1}}$")
24)
25
26knitr::kable(format = "html", a, digits = 35)
27```
28
```

Community Discussions contain sources that include Stack Exchange Network

## Tutorials and Learning Resources in Latex

* Tutorials and Learning Resources are not available at this moment for Latex*