Pretty print sympy when not using iPython - python

I am using SymPy with PyScript so I cannot use init_printing() in my code as I am not running code cell by cell. How can I still use pprint to make my output look good in Web?
Output I am getting:
Output I am expecting:

I wrote a MathJax example that displays formulas correctly: link Right-click on the page to view the source code.
The key is that you must tell MathJax to typeset the answer. This requires dropping down to JavaScript for a simple two line call:
<script>
function draw(str) {
var math = MathJax.Hub.getAllJax("MathDiv")[0];
MathJax.Hub.Queue([ "Text", math, str ]);
}
</script>
Example code including initializing MathJax and setting up the display DIV:
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
<div id="MathDiv">\({}\)</div>
<py-script>
delta__y_l = symbols('Delta__y_l')
latexstr = latex(delta__y_l)
js.draw(latexstr)
</py-script>

Related

plotly graph not rendering in Jinja2 template

Plotly version = '5.12.0'
Jinja2 version = '3.1.2'
I am creating some visuals for a HTML report in python and then emailing them to relevant people. I am using redmail to send the emails.
I am creating a graph using plotly and then converting it to html. This is the code to recreate the graph and produce the html output.
import plotly
import plotly.express as px
from redmail import EmailSender
import jinja2
fig =px.scatter(x=range(10), y=range(10))
graph = fig.to_html(full_html = False, include_plotlyjs ='cdn')
I am then inserting this into my Jinja HTML template which looks as follows
<!DOCTYPE html>
<html>
<body>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
{{graph}}
</body>
</html>
Next, I send the email to the relevant parties using this code
email = EmailSender(
host='smtp.gmail.com',
port=587,
username='email#gmail.com',
password=pwd
)
email.set_template_paths(
html="",
text="",
)
# Create an env
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(''))
email.templates_html = jinja_env
email.templates_text = jinja_env
email.send(
subject="An example email",
sender="example#gmail.com",
receivers=['example#live.co.uk'],
html_template='template_file.html',
body_params= {'graph':graph}
)
The problem is, when I receive the email, it is completely blank, with no data/visuals in it. I should expect to see the plotly scatter plot, or at the minimum the raw text of the plotly graph html.
I have tried pasting the div elements stored in the graph variable into an online HTML viewer, and the graph appears. I have seen other posts suggesting adding {{graph|safe}} to the graph variable in the jinja template, but that does not work either.
I am completely lost as why it is not appearing/rendering in the Jinja template. It is not a problem with redmail as I have used it in the past for other templating work and have managed to insert HTML tables successfully.
Any help would be greatly appreciated.
EDIT: Here is the output of the graph variable outputted by plotly.to_html()
<div> <script type="text/javascript">window.PlotlyConfig = {MathJaxConfig: \'local\'};</script>\n <script src="https://cdn.plot.ly/plotly-2.17.1.min.js"></script> <div id="6a72d392-1672-450b-9d7f-5ad0cd478fd4" class="plotly-graph-div" style="height:100%; width:100%;"></div> <script type="text/javascript"> window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById("6a72d392-1672-450b-9d7f-5ad0cd478fd4")) { Plotly.newPlot( "6a72d392-1672-450b-9d7f-5ad0cd478fd4", [{"hovertemplate":"x=%{x}<br>y=%{y}<extra></extra>","legendgroup":"","marker":{"color":"#636efa","symbol":"circle"},"mode":"markers","name":"","orientation":"v","showlegend":false,"x":[0,1,2,3,4,5,6,7,8,9],"xaxis":"x","y":[0,1,2,3,4,5,6,7,8,9],"yaxis":"y","type":"scatter"}], {"legend":{"tracegroupgap":0},"margin":{"t":60},"template":{"data":{"barpolar":[{"marker":{"line":{"color":"#E5ECF6","width":0.5},"pattern":{"fillmode":"overlay","size":10,"solidity":0.2}},"type":"barpolar"}],"bar":[{"error_x":{"color":"#2a3f5f"},"error_y":{"color":"#2a3f5f"},"marker":{"line":{"color":"#E5ECF6","width":0.5},"pattern":{"fillmode":"overlay","size":10,"solidity":0.2}},"type":"bar"}],"carpet":[{"aaxis":{"endlinecolor":"#2a3f5f","gridcolor":"white","linecolor":"white","minorgridcolor":"white","startlinecolor":"#2a3f5f"},"baxis":{"endlinecolor":"#2a3f5f","gridcolor":"white","linecolor":"white","minorgridcolor":"white","startlinecolor":"#2a3f5f"},"type":"carpet"}],"choropleth":[{"colorbar":{"outlinewidth":0,"ticks":""},"type":"choropleth"}],"contourcarpet":[{"colorbar":{"outlinewidth":0,"ticks":""},"type":"contourcarpet"}],"contour":[{"colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"type":"contour"}],"heatmapgl":[{"colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"type":"heatmapgl"}],"heatmap":[{"colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"type":"heatmap"}],"histogram2dcontour":[{"colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"type":"histogram2dcontour"}],"histogram2d":[{"colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"type":"histogram2d"}],"histogram":[{"marker":{"pattern":{"fillmode":"overlay","size":10,"solidity":0.2}},"type":"histogram"}],"mesh3d":[{"colorbar":{"outlinewidth":0,"ticks":""},"type":"mesh3d"}],"parcoords":[{"line":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"parcoords"}],"pie":[{"automargin":true,"type":"pie"}],"scatter3d":[{"line":{"colorbar":{"outlinewidth":0,"ticks":""}},"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scatter3d"}],"scattercarpet":[{"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scattercarpet"}],"scattergeo":[{"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scattergeo"}],"scattergl":[{"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scattergl"}],"scattermapbox":[{"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scattermapbox"}],"scatterpolargl":[{"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scatterpolargl"}],"scatterpolar":[{"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scatterpolar"}],"scatter":[{"fillpattern":{"fillmode":"overlay","size":10,"solidity":0.2},"type":"scatter"}],"scatterternary":[{"marker":{"colorbar":{"outlinewidth":0,"ticks":""}},"type":"scatterternary"}],"surface":[{"colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"type":"surface"}],"table":[{"cells":{"fill":{"color":"#EBF0F8"},"line":{"color":"white"}},"header":{"fill":{"color":"#C8D4E3"},"line":{"color":"white"}},"type":"table"}]},"layout":{"annotationdefaults":{"arrowcolor":"#2a3f5f","arrowhead":0,"arrowwidth":1},"autotypenumbers":"strict","coloraxis":{"colorbar":{"outlinewidth":0,"ticks":""}},"colorscale":{"diverging":[[0,"#8e0152"],[0.1,"#c51b7d"],[0.2,"#de77ae"],[0.3,"#f1b6da"],[0.4,"#fde0ef"],[0.5,"#f7f7f7"],[0.6,"#e6f5d0"],[0.7,"#b8e186"],[0.8,"#7fbc41"],[0.9,"#4d9221"],[1,"#276419"]],"sequential":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"sequentialminus":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]]},"colorway":["#636efa","#EF553B","#00cc96","#ab63fa","#FFA15A","#19d3f3","#FF6692","#B6E880","#FF97FF","#FECB52"],"font":{"color":"#2a3f5f"},"geo":{"bgcolor":"white","lakecolor":"white","landcolor":"#E5ECF6","showlakes":true,"showland":true,"subunitcolor":"white"},"hoverlabel":{"align":"left"},"hovermode":"closest","mapbox":{"style":"light"},"paper_bgcolor":"white","plot_bgcolor":"#E5ECF6","polar":{"angularaxis":{"gridcolor":"white","linecolor":"white","ticks":""},"bgcolor":"#E5ECF6","radialaxis":{"gridcolor":"white","linecolor":"white","ticks":""}},"scene":{"xaxis":{"backgroundcolor":"#E5ECF6","gridcolor":"white","gridwidth":2,"linecolor":"white","showbackground":true,"ticks":"","zerolinecolor":"white"},"yaxis":{"backgroundcolor":"#E5ECF6","gridcolor":"white","gridwidth":2,"linecolor":"white","showbackground":true,"ticks":"","zerolinecolor":"white"},"zaxis":{"backgroundcolor":"#E5ECF6","gridcolor":"white","gridwidth":2,"linecolor":"white","showbackground":true,"ticks":"","zerolinecolor":"white"}},"shapedefaults":{"line":{"color":"#2a3f5f"}},"ternary":{"aaxis":{"gridcolor":"white","linecolor":"white","ticks":""},"baxis":{"gridcolor":"white","linecolor":"white","ticks":""},"bgcolor":"#E5ECF6","caxis":{"gridcolor":"white","linecolor":"white","ticks":""}},"title":{"x":0.05},"xaxis":{"automargin":true,"gridcolor":"white","linecolor":"white","ticks":"","title":{"standoff":15},"zerolinecolor":"white","zerolinewidth":2},"yaxis":{"automargin":true,"gridcolor":"white","linecolor":"white","ticks":"","title":{"standoff":15},"zerolinecolor":"white","zerolinewidth":2}}},"xaxis":{"anchor":"y","domain":[0.0,1.0],"title":{"text":"x"}},"yaxis":{"anchor":"x","domain":[0.0,1.0],"title":{"text":"y"}}}, {"responsive": true} ) }; </script> </div>

Django refresh data [duplicate]

I am converting one layout to html; once I make the changes in code/html/css, every time I have to hit F5. Is there any simple javascript/jQuery solution for this? I.e. after I add the script, reload the whole page every 5 seconds (or some other specific time).
<meta http-equiv="refresh" content="5; URL=http://www.yourdomain.com/yoursite.html">
If it has to be in the script use setTimeout like:
setTimeout(function(){
window.location.reload(1);
}, 5000);
To reload the same page you don't need the 2nd argument. You can just use:
<meta http-equiv="refresh" content="30" />
This triggers a reload every 30 seconds.
For auto reload and clear cache after 3 second you can do it easily using javascript setInterval function. Here is simple code
$(document).ready(function() {
setInterval(function() {
cache_clear()
}, 3000);
});
function cache_clear() {
window.location.reload(true);
// window.location.reload(); use this if you do not remove cache
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Auto reload page and clear cache</p>
and you can also use meta for this
<meta http-equiv="Refresh" content="5">
setTimeout(function () { location.reload(1); }, 5000);
But as development tools go, you are probably better off with a tab reloading extension.
There's an automatic refresh-on-change tool for IE. It's called ReloadIt, and is available at http://reloadit.codeplex.com . Free.
You choose a URL that you'd like to auto-reload, and specify one or more directory paths to monitor for changes. Press F12 to start monitoring.
After you set it, minimize it. Then edit your content files. When you save any change, the page gets reloaded. like this:
Simple. easy.
Answer provided by #jAndy should work but in Firefox you may face problem, window.location.reload(1); might not work, that's my personal experience.
So i would like to suggest:
setTimeout(function() { window.location=window.location;},5000);
This is tested and works fine.
A decent alternative if you're using firefox is the XRefresh plugin. It will reload your page everytime it detect the file has been modified. So rather than just refreshing every 5 seconds, it will just refresh when you hit save in your HTML editor.
Alternatively there's the application called LiveReload...
If you are developing and testing in Firefox, there's a plug-in called "ReloadEvery" is available, which allows you to reload the page at the specified intervals.
This will work on 5 sec.
5000 milliseconds = 5 seconds
Use this with target _self or what ever you want and what ever page you want including itself:
<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 5000);
}
</script>
<body onload="load()">
Or this with automatic self and no target code with what ever page you want, including itself:
<script type="text/javascript">
function load()
{
setTimeout("location.href = 'http://YourPage.com';", 5000);
}
</script>
<body onload="load()">
Or this if it is the same page to reload itself only and targeted tow hat ever you want:
<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 5000);
}
</script>
<body onload="load()">
All 3 do similar things, just in different ways.
function reload() {
document.location.reload();
}
setTimeout(reload, 5000);

Django and AngularJS: how to display Angular $http errors that come from Django debug error messages

I have a Django view that is called from Angular with a $http.post
//LOADFILE ===================
this.loadfile = function (clickedItem) {
$http.post('/display/' , { "filename": clickedItem.fileName} )
.success(function(data) {
$scope.fileView.text = data;
$scope.fileView.title = clickedItem.title
}).error(function(data) {$scope.displayError=data});
};
If Django throws an error, data will be a full Django error page (full html page).
How do I display that error page (a complete html page) under Angular? (Some discussion of modals here : AngularJS, show popups - The most elegant way?, but nothing about a complete html page...)
I thought I could do this with a frame element and dom:
$window.frames['myErrorFrame'].document.innerHTML = $scope.displayError;
But that doesn't look very Angularish... And this almost does it, but I still have the problem of writing directly to the dom since the src is a string: insert an iframe into page dynamically in AngularJS
Is there a better way to display a full html page string in Angular?
Here is a possible solution. It works, but there are degrees of working, and this is a bit hacky -- the degree zero of working.
The error function (from Write elements into a child iframe using Javascript or jQuery):
update_error = function (message) {
var ifrm = document.getElementById('errorIFrame');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(message);
ifrm.document.close();
};
And the html:
<div ng-show="errorMessage != ''">
<button class="btn btn-info btn-xs" ng-click="errorMessage=''">Close</button><br />
<iframe width="100%" id="errorIFrame"> </iframe>
</div>
The error callback:
.error(function(data) {
update_error(data);
$scope.errorMessage="error"}
Note the switching of the errorMessage flag, which I seem to have to do because update_error is outside the controller (there must be a simple fix for that, but I have other fish to fry). This works, but I imagine it isn't orthodox. There is probably a better way with $sce (will fry that one later).

How to: django template pass array and use it in javascript?

Ok so here is a problem,
I have an html template which looks something like this:
<script>
$(function() {
var vCountries = {{ visitedCountriesList }};
});
</script>
<..>
{{ visitedCountriesList }}
from server I pass an list to this item, but after rendering it looks like this:
<script>
$(function() {
var vCountries = ;
});
</script>
<..>
[u'Afghanistan', u'Japan', u'United Arab Emirates']
so my question is - why ? and how I can pass it to javascript...?
The problem is the string representation of the array isn't valid JavaScript. The u' at the start is no good. This:
[u'Afghanistan', u'Japan', u'United Arab Emirates']
should be this:
['Afghanistan', 'Japan', 'United Arab Emirates']
You have two options. In the view function, encode it as JSON there there:
render_to_response('my_view.html', {
'visitedCountriesList' : json.dumps(visitedCountriesList)
})
or create a filter that you can use. See this one for an example. Then usage is just:
<script>
$(function() {
var vCountries = {{ visitedCountriesList|jsonify }};
});
</script>
you should have in your html an id with the variable rendered and look it there, lets do an example:
<...>
<loldiv id="myvar" data="{{info}}"/>
<...>
and in your javascript:
<script>
$(function() {
var vCountries = $("#myvar").attr("data");
});
</script>
That is assuming you are using jQuery.
I dont really know why that template assign the variable but you should not render any information on javascript code since there is a moment where you are going to take that js and put it on a compressed file, or move it, or reuse it and it will be really hard to do it if you rendered the variable values that way.
hope this helps!

How can I include python script in a HTML file?

How do I put this python script:
a = ['f','d','s','a']
x = -1
scope = vars()
for i in a:
scope['x']+=1
print a[x]
inside of a html file?
Something like this, if you want to create an html, not necessarily display it:
html_file = open('namehere.html','w')
a = ['f','d','s','a']
x = -1
scope = vars()
data = ''
for i in a: #TIP: use a generator
scope['x']+=1
data += a[x]
data += '\n'
html_file.write(data)
html_file.close()
There's now a solution to this, the solution is PyScript. This is a python framework that enables you to embed python scripts in HTML. Check out the sample code below.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-script>
print("Hello World")
</py-script>
</body>
</html>
If your web server supports it, you could run it as a CGI script to output an HTML file - more information here: http://www.penzilla.net/tutorials/python/cgi/
You would need to modify your script to ouput valid HTML, but that tutorial should get you started.
Not possible. Python isn't like PHP; I can't just do this
<?php
And be good to go.
However, if your web server has a Python interpreter (most all do, these days), you can write CGI (common gateway interface) scripts to make Python code run on your webpage.
If you're trying to generate dynamic content (like change words in HTML), Javascript or PHP is better. Python is more suited to web applications.
if the script is in a server , you can run it using remote funcion call through JSON-RPC
you may refer the JSON-RPC documentation here
You can use {% %} tag in html and inside this you can write your python code.
Perhaps CGI is what you are looking for:
http://docs.python.org/library/cgi.html
http://www.penzilla.net/tutorials/python/cgi/
For example:
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<html><head></head><body><pre>"
a = ['f','d','s','a']
x = -1
scope = vars()
for i in a:
scope['x']+=1
print a[x]
print "</pre></body></html>"
Surround it with a <body> and <head> tag and you're golden.
But seriously, I think what you are trying to do is print fdsa, which would would look like this:
<head>
<body>
fdsa
</body>
</head>
What you have there is not really a python script. You might need to correct that first, and then give a little more explanation what you are trying to do.
You can convert the thing into HTML or JavaScript. It would sort of be like this:
<script>
var a = ['f','d','s','a']
var x = -1
//other code
</script>
I am not showing the rest because I am not sure how to make a repeat loop.
You can't. If you want to run script in an HTML File, try another language like JavaScript or PHP. To include javascript, type this:
<script type="text/javascript">
// ...
</script>
Or in HTML5, you don't even have to type the type attribute:
<script>
// ...
</script>
To include PHP, type
<?php
// ...
?>

Categories

Resources