I have written a very simple flask application to test out Bokeh, however my Bokeh line chart just wont render. All it shows is :
My html is:
<html>
<head>
<meta charset="UTF-8">
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-2.0.0.min.css" rel="stylesheet" type="text/css">
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-2.0.0.min.js"></script>
</head>
<body>
{{graph | safe}}
</body>
</html>
My flask function is:
app.route('/result')
def result():
x = [1, 3, 5, 7]
y = [2, 4, 6, 8]
p = figure()
p.circle(x, y, size=10, color='red', legend='circle')
p.line(x, y, color='blue', legend='line')
p.triangle(y, x, color='gold', size=10, legend='triangle')
return render_template("result.html", graph=p)
The version of bokeh currently installed by pip is 2.0.0
You can't just pass a bare Bokeh object to a Jinja template. There are various Bokeh APIs for embedding the content in different ways. You will need to use one of those:
https://docs.bokeh.org/en/2.0.0/docs/user_guide/embed.html
For standalone content like this you either want json_items, components, or autoload_static.
Related
I would like to create a web page that will display data I have in a table inside a code block just the way it is here, even with a copy function.
I can already display the data on the page, I just like to have it formatted in a pretty box, maybe even with syntax highlights, I looked at Pygments but I can't get it to work.
Below is a sample code block that I would like to re-create in my Django app.
Please don't pay attention to the actual code, this is only a sample.
I would appreciate if you could please let me know in detail how to implement this.
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Honestly, your question is more related to CSS and Javascript than Python / Django.
This took me a while...Based on what you said, I will assume you know the basics of Django.
models.py
from django.db import models
class Codeblock(models.Model):
text = models.TextField()
...
views.py
from .models import Codeblock
def codes(request):
codeblocks = Codeblock.objects.all()
return render(request, 'list_codes.html', {'codeblocks': codeblocks})
To format code blocks you can use HTML pre and code tags (Bootstrap 5 examples):
<pre><code>{{codeblocks.text}}</code></pre>
The tricky part was trying to find a way to hightlight the syntax. After a few dead ends I have found highlight.js that worked very well. It has documentation on basic usage and various themes for you to play with, you can test them using this CDN library, it is also possible to write your own theme.
There was one last problem related on how to copy the text. Although it is easy to copy text to clipboard, its not an easy task (at least for me) to have a styled button placed in the right place. To not extend myself, after a while I found this highlightjs-copy project, that not only copy the text to clipboard but has a perfect button in the right place.
With that being said, at last, here is an example:
list_codes.html
<!DOCTYPE html>
<html>
<head>
<!-- bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<!-- highlight.js -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/base16/ashes.min.css" integrity="sha512-KX15mI6Sw0VzQyAOf4MAPS9BZ0tWXyZrGPHKSkqDmy40Jl+79f8ltpj6FvLJ+3obnH56ww0ukclsd6xGAxb5mA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
<!-- highlightjs-copy -->
<script src="https://unpkg.com/highlightjs-copy/dist/highlightjs-copy.min.js"></script>
<link
rel="stylesheet"
href="https://unpkg.com/highlightjs-copy/dist/highlightjs-copy.min.css"
/>
<script>hljs.addPlugin(new CopyButtonPlugin());</script>
</head>
<body style="background-color: hsl(0,0%,22.5%);">
{% for codeblock in codeblocks %}
<div class="container">
<!-- Need to be in one line or will not render correctly -->
<pre><code class="language-python">{{codeblock.text}}</code></pre>
</div>
{% endfor %}
</body>
</html>
I want to change the way tabs are rendered in a bokeh application embedded within a Flask Application, and cannot seem to find a way to do this with my current schema, which is as follows:
Bokeh is created in create_app(), borrowed from their server embed example:
def create_app():
#------------------IRRELEVANT FLASK APP STUFF--------------------------------
bkapp = Application(FunctionHandler(my_gui))
# This is so that if this app is run using something like "gunicorn -w 4" then
# each process will listen on its own port
sockets, port = bind_sockets("localhost", 0)
app._bokehport = port
def bk_worker():
asyncio.set_event_loop(asyncio.new_event_loop())
bokeh_tornado = BokehTornado({'/bkapp': bkapp},
extra_websocket_origins=["localhost:8000"])
bokeh_http = HTTPServer(bokeh_tornado)
bokeh_http.add_sockets(sockets)
server = BaseServer(IOLoop.current(), bokeh_tornado, bokeh_http)
server.start()
server.io_loop.start()
from threading import Thread
Thread(target=bk_worker).start()
return app
my_gui is a bokeh app, very simplified version here:
def my_gui(doc):
def toggleMakeCallback():
rootLayout = doc.get_model_by_name('rootLayout')
listOfSubLayouts = rootLayout.children
p1 = figure(width=300, height=300)
p1.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
tab1 = TabPanel(child=p1, title="circle")
p2 = figure(width=300, height=300)
p2.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=3, color="navy", alpha=0.5)
tab2 = TabPanel(child=p2, title="line")
tabs = Tabs(tabs=[ tab1, tab2 ])
listOfSubLayouts.append(tabs)
make_piece = Button(label="Make Piece", button_type="success")
make_piece.on_click(toggleMakeCallback)
rootLayout = layout(make_piece, name='rootLayout', sizing_mode="scale_both")
doc.add_root(rootLayout)
return doc
In my Flask application this is how I route to the app.
#main_bp.route('/bokehexample', methods = ['GET', 'POST'])
#login_required
def bokehRoute():
script = server_document('http://localhost:%d/bkapp' % current_app._bokehport,
arguments={"id": unsplitId, "teamId": teamId})
return render_template("embed.html", script=script, template="Flask")
Finally, this is embed.html:
<!DOCTYPE html>
<html lang='en'>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='css/embed.css') }}">
<title>PeachPortal - Split Pieces</title>
</head>
<body>
{{ script|safe }}
</body>
</html>
An example of a component of end goal CSS to change the tab design would be as follows:
.bk-root .bk-tabs-header .bk-tab.bk-active{
background-color: green;
color: red;
font-style: normal;
font-weight: bold;
}
I've read and tried and failed with several ways of accomplishing custom CSS (the app just renders the default way no matter what I try):
Adding this css directly in a <style></style> tag in the head of embed.html
Adding this css into the embed.css file referenced in the head of embed.html
Adding this css in the head of embed.html with a django {%include customcss.css%}
Adding a css class such as css_classes =['custom_tab_bokeh'] to my tabs
I've seen another example using curstate, which I don't know how to use in an app context.
I am hoping somebody has successfully changed the CSS for a Bokeh widget using this schema or something similar.
Thank you.
As stated in the docs, you can create a component in a custom path, which is different from the default views/livewire/ and Http/Livewire. Just for the sake of better organization, I created subfolders:
$ php artisan make:livewire tutorial/counter
So I got my files in the following paths:
views/livewire/tutorial/counter.blade.php
Http/Livewire/Tutorial/Counter.php
To test the component in a view, I created a /livewire/tutorial/welcome.blade.php which has the following:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Livewire tutorial: counter</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600;700&display=swap" rel="stylesheet">
<!-- Styles -->
<style>
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}#media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}#media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}#media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}#media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}}
</style>
<style>
body {
font-family: 'Nunito';
}
</style>
#livewireStyles
</head>
<body class="antialiased">
<livewire:counter />
#livewireScripts
</body>
</html>
When I hit the route, I get the following error:
Livewire\Exceptions\ComponentNotFoundException Unable to find
component: [counter]
I already have tried:
$ php artisan livewire:discover
But I still get that error.
What Am I missing?
Solved
Just like Najmus suggested, I tried:
<livewire:path.to.counter />
And that did the trick!
Try this in the welcome.blade.php file
<livewire:tutorial.counter />
instead of
<livewire:counter />
you can create components under subdirectory using php artisan make:livewire users.register User is your folder name and register is component...
and if you want to move existing component then simply you can run this command php artisan livewire:mv register users.register
ie : livewire:mv {your component name} {your folder name}.{component name}
instead of mv you can use move also
may this will help
-Check your class name propely(if any spelling mistake made).
-Check header in class defined or not.
-If component is not there then create one:
php artisan make:liveware component_name
In my case, i typed the extension along with the file name that why it was showing error.
<livewire:abandoned-property-case-list.blade.php/>
But this should be
<livewire:abandoned-property-case-list/>
I downloaded the examples from https://ml5js.org/getting-started/running-examples/ and run them on digital ocean server.
cd /path/to/ml5-examples
python -m http.server 8081
I am running the p5js/PoseNet/PoseNet_webcam/ example
But, it just displays the following, without loading any model.
PoseNet example using p5.js
Loading model...
What i want is to get video stream from webcam on remote server.
EDIT:
My code is:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting Started with ml5.js</title>
<!-- p5 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.sound.min.js"></script>
<!-- ml5 -->
<script src="https://unpkg.com/ml5#0.3.1/dist/ml5.min.js"></script>
</head>
<body>
<script>
// Your code will go here
// open up your console - if everything loaded properly you should see 0.3.1
console.log('ml5 version:', ml5.version);
let capture;
function setup() {
createCanvas(390, 240);
capture = createCapture(VIDEO);
capture.size(320, 240);
//capture.hide();
}
function draw() {
background(255);
image(capture, 0, 0, 320, 240);
filter(INVERT);
}
</script>
</body>
</html>
The JS console gives the following error:
Error: getUserMedia is not implemented in this browser
at Object.navigator.mediaDevices.getUserMedia.navigator.mediaDevices.getUserMedia (p5.dom.min.js:3)
at m.d.createCapture (p5.dom.min.js:3)
at setup ((index):29)
at m.<anonymous> (p5.min.js:3)
at m.<anonymous> (p5.min.js:3)
at new m (p5.min.js:3)
at n (p5.min.js:3)
When i open the program as a local file on the same Chrome browser, there is no error. I only get the error when i run my program on a cloud server.
I am using R Shiny to develop a web page and also include my own R code.
I am using p5.js(https://p5js.org/) to display a game in the web page.
As in the official web page says I have an HTML and the p5 javascript code together with the javascript library. If I run the HTML, that is, clicking right and pressing chrome to display I get the started example (https://p5js.org/get-started/) with no incidence.
Here it is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--<meta name="viewport" content="width=device-width, initial-scale=1">-->
<script language="javascript" type="text/javascript" src="libraries/p5.js"> </script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<!-- this line removes any default padding and style. you might only need one of these values set. -->
<style> body {padding: 0; margin: 0;} </style>
</head>
<body>
</body>
</html>
When I do the same in Shiny, running the code from R-Studio I do not get anything from it. I have stored the javascript files in the www folder as it is supposed to be and I currently know that my HTML called the javascript since I set an alert in the p5 javascript file, but outside the setup and draw methods. The problem is that, even though the alert is loaded, seems like the setup and draw methods are not called and, obviously, as a consequence, they do not load the canvas. I know that they are not called because I have a called to an alert in the setup method that works running the HTML file directly but not if I run the same file from R-Studio.
Here it is the p5 javascript code:
alert("GOOD1");
function setup() {
alert("GOOD2");
createCanvas(640, 480);
}
function draw() {
if (mouseIsPressed) {fill(0);}
else {fill(255);}
ellipse(mouseX, mouseY, 80, 80);
}
I load the HTML page in Shiny using the next line of code
... ,tabItem(tabName = "tabProcessing", htmlOutput("processingMasterThesis") ...
Attach to the tag "processingMasterThesis" I have the corresponding URL to the HTML file in the server.R, as it is supposed to be so the problem is not here.
Why may be the cause of this? It works if I call the HTML file directly to be load in the browser but not if I do it from R-Studio, why?
I have solved the problem. The p5 java script code will be:
// =====================
// "app/sketch.js"
// =====================
var myCanvas;
function setup() {
var idCanvas = 'divCanvas';
myCanvas = createCanvas(300, 300);
myCanvas.parent(idCanvas);
}
function draw() {
if (mouseIsPressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
The library you need to run the example can be found at https://p5js.org/
In this javascript file I have created an id that reference a html div element so that is the place where I will set my canvas. Once this is done, the rest of the javascript code will code perfectly. The point is to reference that the parent of the canvas is that div as you can see in the code.
After this you just have to create either in shiny or pure html code something like this:
# THE UI (File ui.R)
library(shiny)
library(shinydashboard)
library(rmarkdown)
shinyUI(
fluidRow(
# THE UI
tags$html(
tags$body(
singleton(tags$head(tags$script(src = "master_thesis/app/libraries/p5.js")))
,singleton(tags$head(tags$script(src = "master_thesis/app/sketch.js")))
,singleton(tags$div(id = 'divCanvas', style = 'width:auto; height:auto'))
))
)
)
The code that I show below is in shiny. The first "head" line include the library p5.js and the second "head" line just say "hey this is my p5 script file" and "divCanvas will be the div that I will print on".
You may have issues with the references to the javascript file. I think is worthy to note that you must create a www folder in your root shiny application. In this folder, you must put your javascript files. For example, as you can see in my code the two javascript files that I am using follow the next path:
ShinyApplication/www/app/libraries/p5.js
ShinyApplication/www/app/sketch.js
Hope this can help!