Programming in LaTeX

If / else and for loop

Latex is turing complete, but it’s syntax can make it hard to really program. What’s especially confusing, is that oftentimes keywords are not followed by a space, but rather directly by a string. For example if you have the boolean variable foo, you can set it to true using the command footrue, which is a very weird syntax compared to foo = true what we’re used to… However, if you really want to, you can write if’s and loops and do all kinds of stuff… Following is a short tutorial on how to do so.

Booleans and If / Else Statements in Latex

One of the most fundamental parts of any programming language is arguably the boolean data type and it’s logic counterpart the if/else statement. Booleans are part of the latex core, as well as of packages such as the ifthen package.

Booleans and If / Else Without a Package (Option 1)

Booleans can be used in Latex without the use of any packages. However, the syntax is quite cumbersome.

Declaration:

\newif\iffoo %Declaration

Assignment:

\footrue %Sets foo to true
\foofalse %Sets foo to false

Check:

\iffoo
...
\else % else is optional, you can leave it out
...
\fi

Usage example:

\documentclass{article}

\begin{document}
\newif\iffoo %Declaration, defaults to false

\iffoo
text 1
\fi

\footrue % Set foo to true...

\iffoo
text 2
\else
text 3
\fi
\end{document}

Output:Screen Shot 2016-05-22 at 18.45.22

Booleans with the Ifthen Package (Option 2)

When someone is not comfortable with the syntax of the latex core for booleans, he or she might consider to use the ifthen package.

Requirements:

\usepackage{ifthen}

Declaration & Assignment:

\newboolean{boolvar} %Declaration, defaults to false
\setboolean{boolvar}{false} %Assignment

Check:

\boolean{boolvar}

Usage Example:

\documentclass{article}
\usepackage{ifthen}
\begin{document}
\newboolean{boolvar} % Declaration, defaults to false
\ifthenelse{\boolean{boolvar}}{text1}{text2} % If/else with boolean
\setboolean{boolvar}{true} % Assignment
\ifthenelse{\boolean{boolvar}}{text3}{text4} % If/else with boolean
\end{document}

Output: Screen Shot 2016-05-22 at 18.18.29

Integers and Loops in Latex

While integers and loops are an integral part of any programming language, it only occurs to few people to use those concepts in latex outside of the enumeration or itemize environments. Nonetheless it can be done, and here is how.

Integers / Counters

Right next after booleans, or even before them, one usually learns about the data type integers. Latex again has a very peculiar syntax for handling them.

Declaration:

\newcounter{mycounter} %initialized with 0

Assignment:

\setcounter{mycounter}{2} %sets counter to 2

Increment:

\stepcounter{mycounter} % increases mycounter by 1

Get value for programming (e.g. in ifnum condition, see below):

\value{mycounter}

Get value for text output in document:

\themycounter

Adding a number to a counter:

\addtocounter{mycounter}{4}

Adding a counter to a counter:

\addtocounter{mycounter}{\value{myothercounter}}

To compare two counters in an if-clause, the \ifnum-keyword is used:

\ifnum\value{mycounter}>3
Cool beans! % this is only printed if mycounter is larger than 3
\fi

Note: There are also counters in TeX (as opposed to LaTeX), so you might encounter code like \newcount\mycounter elsewhere. The difference between \newcount (TeX) and \newcounter (LaTeX) is minuscule, so make sure you don’t get confused since e.g. calling \value{mycounter} on a counter initialized by \newcount\mycounter will throw an error!

Finally, here’s a complete usage example:

\documentclass{article}
\begin{document}
\newcounter{mycounter} %declare counter, initialized to 0
\themycounter %prints 0
\setcounter{mycounter}{4} %mycounter is now 4
\themycounter %prints 4
\addtocounter{mycounter}{4} %adds 4 to mycounter
\themycounter %prints 8
\addtocounter{mycounter}{-2} %subtracts 2
\themycounter %prints 6
\addtocounter{mycounter}{\value{mycounter}} % adds mycounter to itself
\themycounter %prints 12
\stepcounter{mycounter} % increments mycounter by one
\themycounter %prints 13

\ifnum\value{mycounter}>11
Well yes, \themycounter\ is larger than 11...
\else
...thus this is neverprinted
\fi

\roman{mycounter} %prints mycounter in roman numbers
\end{document}

With it’s glorious output: Screen Shot 2016-05-22 at 20.59.28

Next, we’ll cover how loops can be implemented in LaTeX.

For Loops Without a Package

Since we now have the basics in place to create an integer, compare integers using the operators =, < and > , all we are missing to write a loop is a keyword to do so. The syntax for this is:

\loop \ifsomething
...
\repeat

So a full example would be:

\documentclass{article}

\begin{document}
\newcounter{mycounter}
\setcounter{mycounter}{2}

\loop
\ifnum \value{mycounter} < 5
hello \themycounter,
\stepcounter{mycounter}
\repeat

\end{document}

Output:Screen Shot 2016-05-22 at 19.50.36

For Loops With the forloop package

Requirement:

\usepackage{forloop}

Usage example:

\documentclass{article}
\usepackage{forloop}
\begin{document}
\newcounter{ct}
\forloop{ct}{1}{\value{ct} < 5}{\arabic{ct} }
\end{document}

Output:Screen Shot 2016-05-22 at 17.53.37

For Loops With the pgffor Package

If you prefer a more Python-like syntax, the pgffor package might just be for you. I took the examples from this Stackoverflow answer.

Example Snippet 1:

\foreach \n in {0,...,22}{do something}

Full Example 2:

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\foreach \n in {apples,burgers,cake}{Let's eat \n.\par}
\end{document}

Output: Screen Shot 2016-05-22 at 20.25.45

While Do in Latex with the Ifthen package

Requirement:

\usepackage{ifthen}

Usage Example:

\documentclass{article}
\usepackage{ifthen}
\usepackage{pifont} % for the ding
\begin{document}
\newcounter{ctra} % declare counter, is set to 0
\setcounter{ctra}{3} % set counter to 3
\whiledo {\value{ctra} < 7}
{
 \thectra {\large \ding{111}} % the + counter name prints a counter
 \stepcounter {ctra} % increase the counter by one
}
\end{document}

Output:Screen Shot 2016-05-22 at 18.05.12

Floating Point Numbers (Lenghts in Latex…)

If you read the previous paragraphs, you should get the gist of it by now, so I’ll just provide an example for this one:

\documentclass[varwidth]{standalone}
\begin{document}
\newlength{\mylen} %Declaration
\setlength{\mylen}{3.14pt} %Assignment
The number $\pi$ is approximately \the\mylen\ (think away the pt...).

\addtolength{\mylen}{0.0016pt} %Operator
To be (2 digits) more precise, it's rather \the\mylen.

\settowidth{\mylen}{Text} % measures the width of "Text"
"Text" is \the\mylen\ wide... Crazy stuff.
\end{document}

Which yields the following output:

Screen Shot 2016-05-22 at 22.27.40

Comparison to a Normal Programming Language

Let’s compare the crazy LaTeX syntax to a normal language like Java. The following table can also be used for reference.

LaTeXJavaMeaning & Notes
\newif\iffooboolean foo;Declare a boolean. Defaults to false in LaTeX and null in Java
\footruefoo = true;Set foo to true
\foofalsefoo = false;Set foo to false
\iffoo
%do this
\else
%do that
\fi
if (foo) {
//do this
} else {
//do that
}
If-else statement
\newcounter{n}int n;Initialize integer. Defaults to 0 in Latex and null in Java.
\setcounter{n}{2}n = 2;Set n to two
\stepcounter{n}++n;Increases n by one
\value{n}n;Get value of n for calculations
\then %this is actually a \the immediately followed by n...log.info(Integer.toString(n));Get value of n for print
\addtocounter{n}{4}n += 4;Add 4 to n.
\ifnum\value{n}>12
%do this
\fi
if (n > 12) {
//do this
}
Check if n is larger than 12.
\ifnum\value{n}=12
%do this
\fi
if (n == 12) {
//do this
}
Check if n is equal to 12.
\newcounter{mycounter}
\loop \ifnum\value{mycounter}<5
\themycounter
\stepcounter{mycounter}
\repeat
for (int i = 0; i < 5; i++) {
log.info(Integer.toString(i));
}
For Loop. Prints 0 1 2 3 4
Alternative:
\usepackage{pgffor}
\foreach \n in {0,...,4}{do something}
\newlength{\mylen}float mylen;Create a floating point number. Latex initializes this to 0.0, Java to null.
\setlength{\mylen}{3.14pt}mylen = 3.14;Sets length to 3.14pt in latex and to 3.14 in Java. Since Latex is for typesetting the length must have a unit.
\the\mylenlog.info(Float.toString(mylen));Get mylen for print
\mylenmylen;Get mylen for calculation
\ifnum\mylen<1
%do this
\fi
if (mylen < 1) {
//do this
}
Compare mylen to another number

This article is based on this article here, so thank you Matthias for working this out!

How to Solve Vagrant Spikes CPU to 100% on OSX

Does this look familiar to you…? Then you’ve come to the right place.

Since one year I’ve been developing now using Vagrant and about every day I had to reload the freakin virtual machine because I computer suddenly started getting hot… I’ve been looking for answers but couldn’t find any, until I gave it another shot today. I’ve found a solution for my problem in this thread. So big shoutout for pgrunwald… Anyways, the problem seems to appear when you’re doing port forwarding.

That was my setup when I had the problem:Screen Shot 2016-05-21 at 21.18.05

That’s my setup now:

config.vm.network "private_network", ip: "192.168.3.4"

And THAT’S IT. Now you just have to vagrant reload --provision and you’re Mac won’t go crazy no longer.

Download File From Controller in Angular

Screen Shot 2016-05-20 at 11.05.39

Ever had to download a file from your controller in angular? Then you know the struggle is real. You’ll encounter iframe tricks and filesaver.js and all sorts of stuff. But instead of an iframe trick, what you should really do is a link (<a href=”url”></a>) trick!!!

          var a         = document.createElement('a');
          a.href        = yoururl; 
          a.target      = '_blank';
          a.download    = 'yourfilename.pdf';
          document.body.appendChild(a);
          a.click();

Ta da!!! It’ll download your file!!! Note that the file has to exist on your server. You don’t return the file in a post request, you need a url to an existing file instead. So if you’re looking for how to download the answer from a post request, this you can only use this way if you have access to the server and the server writes an actual file to the file system, which can be accessed from the browser.

Deploying Multiple Meteor Apps on One Ubuntu Server

Meteor makes everything easy. Except for deploying your app on your own server, since they want you to use their solution “Galaxy”. Setting up your own infrastructure can be daunting, especially when you want to host multiple meteor apps on one server. Here I’m going to describe how this can be done using nginx.

Step 1) Configuring nginx

After installing nginx

sudo apt-get update
sudo apt-get install nginx

you can use the following setup in your /etc/ngnix/nginx.conf :

# Change YOUR_TOKEN to your prerender token and uncomment that line if you want to cache urls and view crawl stats
# Change example.com (server_name) to your website url
# Change /path/to/your/root to the correct value

events {
  worker_connections 768;
  # multi_accept on;
}

http {

    upstream project1 {
      server localhost:8081;
    }

    upstream project2 {
      server localhost:8082;
    }

    server {
        listen 80;
        server_name project1.com project1.org;
        client_max_body_size 20M;

        location / {
          proxy_pass http://project1;
          proxy_read_timeout 1000;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
        }
    }

    server {
        listen 80;
        server_name project2.com;
        client_max_body_size  20M;

        location / {
          proxy_pass http://project;
          proxy_read_timeout 1000;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
        }
    }

}

meteordeploy

Step 2) Setting up a meteor project folder

In order to have only one deploy script (aka code duplication is bad), it’s useful to have all meteor apps in one folder. Therefore your directory structure should be somewhat like:

meteor-projects
--project1
--project2

Step 3) Setting up the server

You need to install a bit of stuff on your server in order for meteor to work:

install.sh

#!/bin/bash
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install -y build-essential

#install node
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install nodejs -y

#install npm modules
npm install -g forever
npm install -g phantomjs

#install mongo
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
sudo service mongod start

#install meteor
curl https://install.meteor.com/ | sh

#utils
sudo apt-get install graphicsmagick

Put this somewhere on your server, then chmod +x install.sh and run it ./install.sh.

Step 4) Configuring properties

There are variables to your project, you can put them into a properties.sh file inside of each project:

#!/bin/bash
server=root@46.101.140.209
domain=project1.com
name=project1
port=8081

Note that I’ve set it up in a way, that name should be identical to your folder name.

Step 5) Writing a deploy script

Put those files into your meteor-projects folder:

meteor-projects/deploy.sh

#!/bin/bash
source ${1}/properties.sh

cd ${name}
meteor build compiled
ssh ${server} mkdir ${name}
scp -r compiled ${server}:${name}/compiled
rm -rf compiled
scp ../helper.sh ${server}:${name}/helper.sh
scp properties.sh ${server}:${name}/properties.sh
ssh ${server} chmod +x ${name}/helper.sh
ssh ${server} ${name}/helper.sh

meteor-projects/helper.sh

#!/bin/bash
cd $(dirname $0)
source properties.sh

tar -xvzf compiled/*.tar.gz
rm -rf compiled

# rebuild native packages
cd bundle/programs/server && npm install
cd ~

# setup environment variables
export MONGO_URL="mongodb://127.0.0.1:27017/${name}"
export ROOT_URL="http://${domain}"
export PORT=${port}

# start the server
forever stop ${name}/bundle/main.js
forever start ${name}/bundle/main.js

Things should be ready now!

In order to deploy, perform chmod +x deploy.sh and run ./deploy.sh project1 or ./deploy.sh project2. This should upload & run your meteor files.

Top 6 Google Analytics Features for Beginners

Google Analytics is quite crammed with options, making it hard to find the useful ones. Here’s a list of the most useful features from the reporting tab, the most important one for starting.

Screen Shot 2016-05-14 at 22.20.56

#6 Dashboard

Somewhat hidden under Dashboards > Private > My Dashboard you’ll find the following metrics:

Screen Shot 2016-05-14 at 22.13.28

This gives you a good overview over your users. You see how many new users you’re gaining and how many you have in total and where they’re located. About the bounce rate you shouldn’t worry too. I’d stay clear of focusing too much on improving it, as it will improve naturally if you just provide an interesting page.

#5 Behaviour Flow

Screen Shot 2016-05-14 at 22.07.16

This view can be found under Behaviour > Behaviour Flow. This is interesting, if you have a complex website and you want to reduce the number of clicks a user needs to get to his or her goal.

#4 Pages

Here you can see which pages are doing best:

Screen Shot 2016-05-14 at 23.24.33

It’s found under Behaviour > Site Content > All Pages. This lets you know where you have done an exceptionally good job and what still needs improvement.

#3 Heat Map

In order to see which buttons get used on your page, it’s useful to install the Page Analytics (by Google) plugin for the Chrome Browser.Screen Shot 2016-05-14 at 23.35.07

Using this feedback, you can optimize your website by removing buttons that never get clicked anyways, or position important links more prominently.

#2 Audience Overview (Default Screen)

Screen Shot 2016-05-14 at 22.23.23

Google Analytics sets the default screen to Audience > Overview. Here you can gain a quick overview over what’s happening on your site. Of course you’ll want Sessions and Users to increase. That’s the page you’ll get addicted to, in order to see whether traffic on your page is increasing.

#1 Connecting Search Console with Google Analytics

A really useful screen is Acquisition > Search Console > Queries. But before this will work, you’ll need to connect your search console with Google Analytics. If you don’t have you’re site registered in google search console, you have to do so first. That’s important to be found on Google in any case.

Once you have established the connection, you can see which queries resulted in an impression of your website on Google and how often the search result was clicked:

Screen Shot 2016-05-14 at 23.10.42

So for this page, you see that some impressions were displayed, but none were clicked, which will hurt the ranking in the future. The (not set) is explained by Google like so:

To protect user privacy, queries made a very small number of times or containing personal or sensitive information are grouped as “(not set)”.

It’s possible that the view is not entirely up to date:

No data is available for the 2 most recent days.

Screen Shot 2016-05-15 at 15.33.04

The SEO view is so important, because it lets you know where you rank good on Google and where you could improve. For example, if something has 100 impressions but no clicks, you might consider putting a better description on the page. Or when you already rank good in “bla” for a page, you might consider to optimize the page even more for “bla” so it’ll get to Google page one, increasing your user numbers.

Best WYSIWYG Editor for Web-Content

Logos of different WYSIWYG editors for web content / html

UPDATED: June 2017

There are different out of the box wysiwyg’s for the web. Prominent exponents of web-html-wysiwyg’s are the CKEditor or the TinyMCE. Paid (yet still extendable) solutions include Froala and Redactor. Which one’s right for you?

TL;DR: If you’re commercial, use the Froala Editor. If you’re not or need an open source editor use TinyMCE.

Here’s a more comprehensive breakdown of all editors.

CKEditor

The CKEditor is the most broadly adopted Wysiwyg editor nowadays. Google trends confirms this compared to it’s main competitor TinyMCE. Yet, I completely do not understand how it got there. It’s quickly installed, I’ll give it that much. But the developers seem not to have the slightest clue about design or usability. Here’s how it looks like:

CK Editor Screenshot

It looks very heavy and old-fashioned. But the problem really starts when looking at the more complex features. Like inserting a table.

CK Editor Table Insertion

I think this interface speaks for itself.

The next atrocity follows once you have the table input inserted:

CKEditor Tables

Yes, I know this is how browsers render tables historically, but couldn’t the editor somewhat ease the pain? Every other editor I found doesn’t display it like this.

Anyways, let’s move on and insert an image:

CKEditor Image Insertion

Again, we are confronted with a beautifully designed dialog. Not. I don’t want to waste anymore space, so I’ll not post more CKEditor popup dialogs. So what are the good parts about the CKEditors? Well, there are plugins, it’s customizable and it’s got broad adoption so you’ll find some help for your problems on the interwebz.

One other thing I noticed, is that CK is more aggressively converting your input than other editors. For example a tick (‘) is left alone by most editors, while CK converts it to &#39;. Whether you find this good or bad depends on what you want. By the way, did you know that the CKEditor used to be the FCKEditor named after it’s creator Frederico Caldeira Knabben, but then they noticed fck is too close to f*ck?

TinyMCE

Ah, away from the horrors that is the CKEditor and onwards to adventures with TinyMCE. The name means it was “Tiny Many Centuries Earlier”. Which is not that bad, computers get faster, but some people in the community don’t like it.

So at first sight TinyMCE looks nicer than the CKEditor.

TinyMCE Screenshot

I understand most of it’s elements as only the common ones are itemized and for the others they use dropdown menu’s and text-labels. If you haven’t given this too much thought, here’s why this is a good move. Let’s continue by inserting a table:

TinyMCE Table Insertion

What I like about it, is the grid-selection of the table size. What I don’t like about it is, that it show’s 1 option which is clickable and 5 options which aren’t.

TinyMCE useless buttons

Why is it showing this to me? Well anyways, this is a detail. Afterwards, the inserted table looks nice and I get options to edit it:

TinyMCE table editing

So all-in-all the TinyMCE table experience is satisfactory but not overwhelming. Let’s perform an image upload next. Oh that’s right, I can’t. I can only link a URL where my image is. That’s really handy of course, since I always upload my images first to another server, before using them on the actual platform! Great!

TinyMCE image insertion

Of course, for any image upload to a server, the editor can’t do it by itself, but I think it should at least provide the interface and explain how you can wire it to your server.  I tried to Google for a workaround, but wasn’t finding anything fast, which is usually a bad sign. On the other hand, I’m sure there are things and even if there are not, adding a “Add Media” button yourself won’t be too hard. Actually, WordPress does it like that:

Wordpress Add Media Button

They use the TinyMCE with an external button to upload media. So if TinyMCE is good enough for WordPress, it will surely be good enough for you? Well, consider that WordPress has been around for quite a while and so has TinyMCE and it thus just might be a legacy choice. Also, WordPress has to use open source code in order to be able to distribute it. The next option will be a paid one, so if your solution doesn’t need to be open source, you might consider it.

Froala

Ahh isn’t this a bliss? Start’s really nicely. Until you notice it’s not free.

Well, can I still customize it? Yes, you can. You can write plugins https://www.froala.com/wysiwyg-editor/docs/concepts/create-plugin for this editor, as well as for CK or TinyMCE. The only difference is that it will make you between $99 and $799 poorer, while looking better. Let’s see whether the table feature and images are implemented better than in CK or TinyMCE. That’s really the anything hard for a wysiwyg anyways. Making something bold I could even do myself… So, tables:

Froala Table Insertion

That’s all I need for inserting! Thank you! Editing tables:

Screen Shot 2016-05-12 at 01.42.58

I can only say one thing: Very sophisticated and thought through. Borders are draggable and stylable and individual cells are even colorable.

Froala Tables

What about images?

Froala Image Insertion

YES, this is what I need! First priority: UPLOAD. If you really want to, then fine, click that darn link so you can insert an image by URL. How does it look like once it’s inserted?

Froala Image Editing Part 1Froala Image Editing

Wow, I can resize it and everything! That’s just great.

I want to conclude the summary about Froala with a statement that I’m not affiliated with them or their product. Simply the frustration about CK and Tiny got me to be so excited about something that will cost you 800 bucks for commercial use. Following are some more editor’s, just not described as in detail anymore.

Update

I wrote this review originally about Froala Editor v1. Now they have released a v2, and it’s even better. We’re now using the Froala Editor in our product Taskbase including customizations. Their API is intuitive and it was a joy to work with it. With only 300 lines of code I managed to strap together a math plugin, gap text plugin and a special list feature. All the options of the editor are well documented and useful. They found a good balance between powerful features yet not overloading the editor and it is really well designed (code as well as layout). When you buy the editor, you can download the full source code. However, I would not recommend you to “hack their core” (google hacking core if you haven’t heard of this), but instead to write plugins. This way you’re sure to stay compatible with their updates.

Like what you're reading?    Get the latest updates first!

No spam. Just great engineering posts.

Redactor

Next to Froala, there is another paid wysiwyg editor. It’s called Redactor. Redactor has less features than Froala. They only allow for full-width images and full-width tables. Furthermore tables cannot be stacked into each other or customized. Those restrictions might be exactly what some people are looking for.

Redactor Screenshot

However, I think even if you want a simplistic editor Froala is the better choice. You may easily take out a lot of functionality out of Froala (e.g. not displaying a file upload button or a change-color button) but once you decide afterwards you want those things anyhow, you’ll be damn glad the editor already has them and you don’t have to program it yourself!

QuillJS

Screenshot of the QuillJS editor

QuillJS is a a nice option if you want an editor that works without JQuery, for example if you need to use the ShadowDOM. It’s an open source project you can find on Github at https://github.com/quilljs/quill with over 13k stars.

On the downside it doesn’t offer extended functionality like for example tables.

ContentToolsJS

While ContentToolsJS also has a strong focus on beauty, it throws overboard quite a lot of the classical editor notion. Their editor just dangles in the air, which I imagine could become a problem on mobile phones? Also I couldn’t find anything about cusomizability, so I expect that I couldn’t write any plugin for it. Last but not least, let’s inspect our favourite quality give-away element, the table:

ContentToolsJS Screenshot

It’s not customizable at all and always equidistant (here ⅓, ⅓,⅓ ). So if you Have a lot of text in let’s say column two and three and only labels in column one, then you’re “the former name of ck-editor-ed”

SimpleMDE

While all the other editors discussed so far were HTML editors, let’s review a markdown editor for a change. It’s easier to write a markdown editor because it’s only a subset of the html features, but on the other hand you’ll have to live with those restrictions afterwards. SimpleMDE has done a good job with bold, italics, headings and so on. As usually. It’s left out tables even though those would be supported by Markdown. Shame on you SimpleMDE! Still the best Markdown-Almost-Wysiwyg out there.

SimpleMDE Screenshot

Other Editors

I’ve tried a bunch of other editors like Trubowyg, textAngular or Summernote. I’ll just say they didn’t really convince me and leave it at that. Choose Froala and go out and play rather than reading about more editors!

Just for fun: If you want to see how Wikipedia does it, you can! Just click on “edit” in Wikipedia. For the German pages, they have a quite elaborate editor catering to almost any need:

Wikipedia Editor Screenshot

Conclusion

I wouldn’t have thought it’s so damn hard to find a decent wysiwyg in 2016. But apparently it is. If you need an open source solution and can’t spare a few bucks, TinyMCE is the best option. If you don’t mind spending a little money or it would be more expensive for you to program your custom “Add Media” button, choose Froala. If you don’t want to take my word for it, here’s another review.

MathJax vs KaTeX vs MathML vs Latex2Img

MathOnWeb

There is a multitude of options to display mathematics on the web including MathJax, Katex, MathML and Latex2Image. Which one is right for you?

TL;DR: Choose Mathjax.

Mathjax

Mathjax can work with latex or mathml input, then sends the code to the mathjax library which renders a “mathjax element”. This is a svg with fonts, which can also be copy pasted (right click). Are there limitations? Mathjax can render most of the “standard” Latex. So as long as your users don’t wanna go too crazy (e.g. tikz or some other specialized library), you’re fine with Mathjax. The major advantage is that it’s svg and thus looks “beautiful”, and you also do not need to compile every equation yourself. Often you’ll read that mathjax is a bit slow. But I found that even with lots and lots of math on the page, it would render fast.

The idea behind mathjax is not to do everything with mathjax, but to leave things like bold-font and italic to the html and only cover the mathematics of the page.

For example in Latex, you’d write:

Hello \textbf{World}, let's do some math: $\frac a b = c$

whereas in mathjax the equivalent for this is:

Hello <b> World </b>, let's do some math: $\frac a b = c$

Notice how the bold font is just regular html, it has nothing to do with mathjax. Mathjax only covers the mathematics on the page.

Mathjax keeps things nice and simple, you can choose delimiters for inline math (e.g. $ to start and $ to end as we’re used from latex) and for “display-math” (meaning a centered block element).

It’s very easy to get started with it, just import the mathjax library and optionally configure the mathjax object. Mathjax will do the rendering from there. Here’s an example config for the mathjax object:

MathJax.Hub.Config({
  tex2jax: {
    inlineMath: [['$','$'],['\\(','\\)']],
    displayMath: [['$$','$$'],['\\[','\\]']],
    balanceBraces: true,
    processEscapes: true,
    processRefs: true,
    processEnvironments: true,
    ignoreClass: "no-mathjax"
  },
  TeX: {
    equationNumbers: { autoNumber: "AMS" },
    extensions: ["[Contrib]/siunitx/unpacked/siunitx.js"],
    Macros: {
      mustbe: "\\overset{!}{=}",
      RR: "\\mathbb{R}",
      ZZ: "\\mathbb{Z}",
      NN: "\\mathbb{N}",
      QQ: "\\mathbb{Q}"
    }
  }
});

Here are the cornerstones explained:

  • inlinemath, displaymath: Delimiters for mathematics. Note that $ some math $ is NOT the default for inline-math, the default is \( some math \)!
  • ignoreClass: For example if you want to parse your entire page for mathematics except some parts, you can exclude those parts by surrounding them with the css-class specified in ignoreClass.
  • Macros: Macros as you’d know them from Latex
  • extensions: In case default Mathjax isn’t enough, it’s also possible to use (or write) additional extensions

Finally, here’s an example of some rendered Mathjax inline \( \int_0^\infty x^2\) and block \[\sum_{n=0}^3 n-3 = … \]

KaTeX

While with Mathjax there seem (almost) no Latex features missing, KaTeX can’t render a number of equations such as \overrightarrow{AB} or aligned equations. This disqualifies Katex for the moment being. Once it hosts a more comprehensive latex-feature set, it becomes a viable alternative to Mathjax, because it renders much faster. However, we never experienced any problems with the speed of mathjax, so I don’t really see the need.

MathML

The advantage of MathML is, that it can be interpreted by the browser. So for example, when you write <math xmlns=”http://www.w3.org/1998/Math/MathML“><mfrac><mn>1</mn><mn>2</mn></mfrac></math> into your html, the browser will display ½. Actually, let’s rather say it should, since it doesn’t work e.g. with Chrome Browser but does work with firefox. When you type $\frac 1 2$, the browser will display $\frac 1 2$ (unless you use mathjax). Overall, it can be said that this is a very shaky way to display your math and I don’t see any reason to do so.

A look at Google trends reveals, that MathML is clearly de-trending and being surpassed by Mathjax.

Converting Latex to image (png,svg,…)

That’s the way Wikipedia does it. On the downside, you’ll have to handle all the scaling and storing of images yourself. On the upside, there isn’t anything from latex, that can’t be rendered, and it’s fast. There are also two possibilities here: Either you only compile equations or you compile the entire thing. Compiling the entire thing is rather bad, since it’s not scalable width wise and all the text is not selectable anymore.

Bonus Option: Mixed

Since Mathjax perfectly handles most of the latex, it can be safely used for displaying math of a web page, for example together with a wysiwyg editor. However, sometimes you want to have the crazy latex stuff like tikzpictures anyways. There’s nothing wrong with combining mathjax and latex2image. You can handle the simple math with Mathjax and the the advanced latex stuff with a “latex” plugin for your wysiwyg editor.

Here’s what this could look like:

Bla bla bla it’s still html now some mathjax \(\frac a b = c\) and for the complex stuff latex2img like here:

latex2img

Conclusion

It’s a close race between Mathjax and compiling equations with latex to png’s and displaying them as images. I would recommend the Mathjax option, since Mathjax has gained wide support and will improve over time and saves development time. Also, when done correctly, Mathjax rendering can be quite fast.

To be sure not to make the wrong decision, take an example from Quora.com:

Read Stephanie Ho‘s answer to Should Quora use MathJax to display equations? on Quora

Password-protect Parts of Your Website

password-protect (2)

Prerequisites

You will need a running ubuntu server to follow the steps in this article.

Setup

  1. Enter in terminal:
    sudo apt-get update
    sudo apt-get install apache2 apache2-utils
    sudo htpasswd -c /etc/apache2/.htpasswd some-username
    sudo nano /etc/apache2/sites-enabled/000-default.conf
    
  2. Add:
    <Directory "/var/www/html">
            AuthType Basic
            AuthName "Restricted Content"
            AuthUserFile /etc/apache2/.htpasswd
            Require valid-user
    </Directory>
    

    Replace /var/www/html with the path to the directory you want to restrict access to.

  3. sudo service apache2 restart

Voila!

Host Static Files with Apache on Digitalocean

1. Setup Digital Ocean Server

Login or create an account and spin up a new ubuntu 14.04 droplet at www.digitalocean.com, it is pretty self explanatory. In the options, you should choose login through SSH if you want to follow this article step by step.

Then login to your Server:
ssh root@<yourIp> (e.g. ssh root@46.101.131.21).

2. Install Apache

sudo apt-get update
sudo apt-get install apache2
When you type <yourIp> into your browser (e.g. Screen Shot 2016-04-29 at 12.12.09), you should now be able to see the following:
Screen Shot 2016-04-29 at 12.10.23

3. Change index.html

Now “hosting static files” can mean two things. Either you want to host something like mycoolfile.txt or you want a classic website.

Option 1: Host files for downloading

  1. Switch directory to cd /var/www/html and remove the index.html file (rm index.html)
  2. Copy the files to your server. Navigate to the directory containing your file in a new terminal window and scp mycoolfile.txt root@<yourIp>:/var/www/html.

You should see the following result when navigating to yourIp in your browser:

Screen Shot 2016-04-29 at 12.40.03

Option 2: Host your personal website

  1. Switch directory to cd /var/www/html and remove the index.html file (rm index.html)
  2. Then nano index.html. Then you can write any valid html, for example:
    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>Much Doge! Wow!</h2>
    <img src="https://s-media-cache-ak0.pinimg.com/736x/ee/b7/71/eeb771122eebac79dda2eb99d43e3d82.jpg" alt="Doge" width=300px>
    
    </body>
    </html>
    

    which should yield:
    Screen Shot 2016-04-29 at 12.54.40

 

Install SSL certificate through letsencrypt on nginx

The days of expensive SSL Certificates are over. Letsencrypt is rapidly changing the way certificates are handled. The basic functionality is that you install the letsencrypt client on your server and from there it does its magic to authenticate your server. They also offer a lot of automation tools, which might scare you at first. But it’s really easy to get certificates and install them e.g. with nginx. Here’s how, assuming you have nginx installed on an ubuntu server.

1) Go to your registrar and point your site, e.g. example.com to your servers IP e.g. 107.170.33.76.

2) Login to your server (ssh root@107.170.33.76 on digital ocean for example), then:

git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt
./letsencrypt-auto certonly --standalone --email youremail@gmail.com -d example.com -d www.example.com
cd /etc/nginx/ssl/
ln -s /etc/letsencrypt/live/taskbase.com/privkey.pem nginx.key
ln -s /etc/letsencrypt/live/taskbase.com/fullchain.pem nginx.crt

3) Use the following inside your http block of the nginx.conf file:

  upstream project {
    ip_hash;
    server localhost:8080;
  }

  server {
    listen  80;
    server_name example.com www.example.com;
    return  301 https://$host$request_uri;
  }

  server {
    listen 443 ssl;
    server_name example.com www.example.com;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;

    location / {
      proxy_pass http://project;
      proxy_read_timeout 1000;
    }
  }

4) service nginx reload and enjoy.