MathJax not processing latex environments - javascript

I am writing a blog post on blogspot. Here is my MathJax configuration in the theme's html file.
<script defer='defer' id='MathJax-script' src='https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-svg.js' type='text/javascript'/>
<script>
window.MathJax = {
tex: {
loader: {load: ['[tex]/ams']},
inlineMath: [ ['$','$'],['\\(','\\)'] ],
displayMath: [ ['$$','$$'], ['\\[','\\]'] ],
processEscapes: true,
processEnvironments: true,
processRefs: true,
packages: {
'[+]': ['ams']
},
},
};
</script>
And here is my attempt at using the amsmath align environment.
...
By linearity of expectation
\begin{align}
\mathbb{E}[I_r] & \leq |I_{r-1}|+\sum_{u\in \overline{I_{r-1}}\setminus \{v_{r-1}\}}{\mathbb{E}[X_{u,r}]}+1\\
& \leq |I_{r-1}| + c_2k(|\overline{I_{r-1}}|-1)|I_{r-1}|/n^2+1\\
& \leq |I_{r-1}|\cdot(1+c_2k/n) + 1\\
\end{align}
...
However, when previewing my page, it just renders the text literally, without MathJax processing. How can I fix this?

This works perfectly. Hope it works for you.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
MathJax = {
tex: {
inlineMath: [
['$', '$'],
['\\(', '\\)']
]
},
svg: {
fontCache: 'global'
}
};
</script>
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-chtml.js">
</script>
</head>
<body>
<div class="math">
\begin{align}
\mathbb{E}[I_r] & \leq |I_{r-1}|+\sum_{u\in \overline{I_{r-1}}\setminus \{v_{r-1}\}}{\mathbb{E}[X_{u,r}]}+1\\
& \leq |I_{r-1}| + c_2k(|\overline{I_{r-1}}|-1)|I_{r-1}|/n^2+1\\
& \leq |I_{r-1}|\cdot(1+c_2k/n) + 1\\
\end{align}
</div>
</body>
<script>
const
math = document.querySelector('.math')
MathJax.typeset();
</script>
</html>

Related

How can I use javascript library function in nuxt.js?

This source worked in html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kakao JavaScript SDK</title>
<script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
<script>
// SDK를 초기화 합니다. 사용할 앱의 JavaScript 키를 설정해 주세요.
Kakao.init('JAVASCRIPT_KEY');
// SDK 초기화 여부를 판단합니다.
console.log(Kakao.isInitialized());
</script>
</head>
<body></body>
</html>
So I thought the next source will work on Nuxt.js.
But it showed just
'ReferenceError
Kakao is not defined' in these source
in nuxt.config.js
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
title: 'P-Cloud OCR',
meta: [
{ 'http-equiv': 'X-UA-Compatible', content: 'IE=Edge' },
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
script: [
{ src: 'https://developers.kakao.com/sdk/js/kakao.js'},
]
}, ```
in pages/login.vue
<script>
export default {
...
}
Kakao.init('JAVASCRIPT_KEY');
console.log('Kakao.isInitialized() >>', Kakao.isInitialized());
</script>
Why is this source not working?
There are basically 2 approaches you can do:
1. Load the library directly in your layout/page/component
head () {
if (window.Kakao) {
this.afterKakaoLoaded()
return
}
return {
script: [
{
hid: 'kakao',
src: 'https://developers.kakao.com/sdk/js/kakao.js',
callback: () => {
this.afterKakaoLoaded()
}
}
]
}
},
methods: {
afterKakaoLoaded () {
window.Kakao.init('...')
}
}
2. Load the library within a plugin
Josh Deltener wrote a great article about how to achieve that: https://deltener.com/blog/nuxt-third-party-code-is-poison/
In nuxt you can overwrite the default .nuxt/views/app.template.html.
You need to create app.html file at the root of the project. Then put the below code inside this file:
app.html
<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
<head {{ HEAD_ATTRS }}>
{{ HEAD }}
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
Then you can follow the traditional way that you mentioned in question:
<!DOCTYPE html>
<html lang="en" {{ HTML_ATTRS }}>
<head {{ HEAD_ATTRS }}>
{{ HEAD }}
<script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
<script>
// SDK를 초기화 합니다. 사용할 앱의 JavaScript 키를 설정해 주세요.
Kakao.init('JAVASCRIPT_KEY');
// SDK 초기화 여부를 판단합니다.
console.log(Kakao.isInitialized());
</script>
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
But be aware that in this method, all pages in your application load this script.

Passing data in array that came from an array to chartjs with django

So, I'm trying to pass some data to a chart (using chartjs and django) and I can print my data in my webpage, but can't pass it as arguments to the chart. Also, if I put data hardcoded in the chart it works, but with my own data from an array I can't see anything...
I've tried {{data | safe}} and {{labels | safe}} but I get an error, so I'm not getting what I'm doing wrong. Can anyone help me?
To explain better:
views.py
import csv
def home(request):
csvFilePath = "../data/raw_datasets/covid_confirmed.csv"
data = []
labels = []
with open(csvFilePath, "r") as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
next(csv_reader)
for row in csv_reader:
data.append(row[1])
labels.append(row[73])
return render(request, 'home.html',
{
'data': data,
'labels': labels
})
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<title>Crypto Covid</title>
</head>
<body>
<h4>{{data | safe}}</h4>
<p>--------------</p>
<h4>{{labels|safe}}</h4>
<div class="container">
<canvas id="chart">
</canvas>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<script> src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"</script>
<script>
var config = {
type: 'pie',
data: {
datasets: [{
data: {data} ,
backgroundColor: [
'#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3'
],
label: 'Population'
}],
labels: {labels}
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById('chart').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
</html>
The result in my page:
my result page
you need to use template tag called json_script, {{ your_array|json_script:"chart_data" }} and then access this data in javascript -
var value = JSON.parse(document.getElementById('chart_data').textContent);
https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#json-scriptDjango documentation
Try this please
import csv
def home(request):
csvFilePath = "../data/raw_datasets/covid_confirmed.csv"
data_list = []
with open(csvFilePath, "r") as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
next(csv_reader)
for row in csv_reader:
data_list.append({'label' : row[73], "y" : row[1]})
t = json.dumps(data_list)
return render(request, 'home.html',
{
'output':t
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<title>Crypto Covid</title>
</head>
<body>
<div id="pie-chart" style="width: 100%;height:370px;">
</div> <!-- edited -->
</body>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> <!-- edited--></script>
<!-- edited -->
data = JSON.parse("{{ output|escapejs }}")
window.onload = function() {
var chart = new CanvasJS.Chart("pie-chart", {
type: 'pie',
data: [{type: "pie",dataPoints: data}],
options: {
responsive: true
}
});
chart.render();
};
</script>
</html>
Try passing the data list by list (I use render_template on Flask) and retrieve it on javascript (as an array) with:
labels: [{% for item in families %}
"{{ item }}",
{% endfor %}]
...even if pylint may say criticize the html syntaxe. It runs well.

Stripe Checkout is not defined reference error

I am trying to put Stripe into my web page to accept payments. But whenever I load the page I get an error saying that stripeCheckout is not defined. I know this has to do with the library imported in one of my script tags, but I am not sure why it is showing up as undefined. The library imported I thought was correct. Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- CSS Link -->
<link rel="stylesheet" href="styles.css">
<title>Store</title>
<script src="https://checkout.stripe.com/checkout.js" defer></script>
<script>
var stripePublicKey = '<%= stripePublicKey %>'
</script>
<script src="store.js" defer></script>
</head>
and this in my store.js file
const stripeHandler = stripeCheckout.configure({
key: stripePublicKey,
locale: 'auto',
token: function(token){
}
})
// Removes cart items after they are purchased
const purchaseItems = () => {
// let cartItems = document.getElementsByClassName('cart-items')[0]
// while(cartItems.hasChildNodes()){
// cartItems.removeChild(cartItems.firstChild)
// }
// updateCartTotal()
let priceElement = document.getElementsByClassName('cart-total-price')[0]
let price = parseFloat(priceElement.innerText.replace('$', '')) * 100
stripeHandler.open({
amount: price
})
}
I believe that that particular Stripe checkout API (and script) is now deprecated.
Here's a link to the docs for the new APIs: https://stripe.com/docs/payments/checkout/migration#client-products
Example from docs:
// client.html
<script src="https://js.stripe.com/v3"></script>
<button id="checkout-button">Pay</button>
// client.js
var stripe = Stripe('YOUR_API_KEY');
var checkoutButton = document.querySelector('#checkout-button');
checkoutButton.addEventListener('click', function () {
stripe.redirectToCheckout({
items: [{
// Define the product and SKU in the Dashboard first, and use the SKU
// ID in your client-side code.
sku: 'sku_123',
quantity: 1
}],
successUrl: 'https://www.example.com/success',
cancelUrl: 'https://www.example.com/cancel'
});
});

How can I use MathJax or LaTex in an html file?

I cannot get it to work and I'm not sure what I'm doing wrong.
I've downloaded MathJax.js, created an html file and linked it to the js file appropriately. I even copied and pasted from a previously answered question on here and just changed the link from a vpn (the vpn didn't work either, but the question and response were over three years old) to the js file on my machine.
Here's what I have in my html:
<html>
<head>
<title>MathJax</title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({"HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"] },
tex2jax: { inlineMath: [ ["$", "$"], ["\\\\(","\\\\)"] ], displayMath: [ ["$$","$$"], ["\\[", "\\]"] ], processEscapes: true, ignoreClass: "tex2jax_ignore|dno" },
TeX: { noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } } },
messageStyle: "none"
});
</script>
<script type="text/javascript" src="MathJax.js"></script>
<script type="text/javascript" src="latest.js"></script>
</head>
<body>
The definition of the Euler-Mascheroni constant is
\gamma=\lim_{n\to\infty}\left(\sum_{k=1}^n\frac1k-ln(n)\right)
</body>
</html>
I would greatly appreciate any assistance.
There are a few problems.
If you don't specify a so-called combined configuration file, you need to specify all necessary components yourself. In particular, input, output and in your case the TeX pre-processor to find TeX markup in the page
If you use TeX input, you need to wrap input in the delimiters of your choice.
For example
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
jax: ["input/TeX", "output/HTML-CSS"],
extensions: ["tex2jax.js"],
"HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"] },
tex2jax: { inlineMath: [ ["$", "$"], ["\\(","\\)"] ], displayMath: [ ["$$","$$"], ["\\[", "\\]"] ], processEscapes: true, ignoreClass: "tex2jax_ignore|dno" },
TeX: { noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } } },
messageStyle: "none"
});
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js"></script>
The definition of the Euler-Mascheroni constant is
$\gamma=\lim_{n\to\infty}\left(\sum_{k=1}^n\frac1k-ln(n)\right) $
Caveat. I don't know what latest.js should do and you seem to be using a local installation so be sure to check the docs for that, http://docs.mathjax.org/en/latest/installation.html.
Here is a file I constructed from the documentation examples
<html>
<head>
<!-- See http://docs.mathjax.org/en/latest/web/start.html#using-mathjax-from-a-content-delivery-network-cdn -->
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-chtml.js">
</script>
</head>
<body>
<p>
From the overview docs, in MathML: Let's consider <math><mi>a</mi><mo>≠</mo><mn>0</mn></math>.
</p>
<p>
With \(\LaTeX\) input:
When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are
$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</p>
</body>
</html>

Dojo DataGrid filter using an AndOrReadStore - what am I doing wrong?‏

I have the following code working with a DataGrid that has two column Column_A and Column_B respectively:
grid.filter({Column_A: '*test*', Column_B: '*'}, true)
This code works fine and finds all rows where Column_A has the word test in it... now, I'd like to do the same but look in either column.... the comma translates to an AND operation but I am looking for an OR operation.
I read the AndOrReadStore specs and based on my understanding I should be able to do something like this:
grid.filter({complexQuery: "Column_A: '*test*' OR Column_B: '*'"}, true)
however this does not work and I don't get any results... I can't even get it to work with one column, like this
grid.filter({complexQuery: "Column_A: '*test*'"}, true)
What am I doing wrong?
Thank you
Here is a working programmatic example (Click the button to invoke the filter: Column_A contains an e OR Column_B is 300):
the JavaScript (script.js):
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.form.Button");
dojo.require("dojox.grid.DataGrid");
dojo.require('dojox.data.AndOrReadStore');
dojo.ready(function(){
var appLayout = new dijit.layout.ContentPane({
id: "appLayout"
}, "appLayout");
var data = {
'items': [
{'Column_A': 'alpha', 'Column_B': '100'},
{'Column_A': 'beta', 'Column_B': '200'},
{'Column_A': 'gamma', 'Column_B': '300'},
{'Column_A': 'delta', 'Column_B': '400'}
]
};
var store = new dojox.data.AndOrReadStore({
data: data
});
var layout = [[
{name : 'A', field : 'Column_A', width : '125px'},
{name : 'B', field : 'Column_B', width : '100%'}
]];
var grid = new dojox.grid.DataGrid({
structure : layout,
store: store,
queryOptions: {ignoreCase: true}
});
var filterButton = new dijit.form.Button({
label: "Filter",
onClick: function () {
grid.filter({complexQuery: "Column_A: '*e*' OR 'Column_B: '300'"});
}
});
filterButton.placeAt(appLayout.domNode);
grid.placeAt(appLayout.domNode);
appLayout.startup();
});
And now the html (index.html)
<html lang="en">
<head>
<meta charset="utf-8">
<title>DataGrid with AndOrReadStore</title>
<link rel="stylesheet" href="style.css" media="screen"/>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dijit/themes/claro/claro.css" />
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dijit/themes/claro/document.css" />
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojox/layout/resources/ExpandoPane.css" />
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojox/grid/resources/claroGrid.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojox/grid/enhanced/resources/claro/EnhancedGrid.css">
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body class="claro">
<div id="appLayout"></div>
</body>
</html>
And finally the css (style.css)
html, body {
width: 100%; height: 100%;
margin: 0; padding: 0;
overflow: hidden;
}
#appLayout {
width: 100%; height: 100%;
}
I looked at the link you posted, and I think it's an issue of getting the brackets and parenthesis correct. Also, it looks like the 'complex query' is used for objects, whereas 'query' is used for strings:
grid.filter({query: ("Column_A: '*test*' OR Column_B: '*'")}, true);
Here's the link I looked at: http://dojotoolkit.org/reference-guide/dojox/data/AndOrReadStore.html#dojox-data-andorreadstore

Categories

Resources