How to send image using flask Socket-Io - sockets

I am very novice in Flask Socket.IO, I am trying to find a solutions where I can send images using Flask Socket.IO. Help would be highly appreciated.
I am using this application.py file to emit a saved image from the project directory
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
__author__ = 'slynn'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)
#random number Generator Thread
thread = Thread()
thread_stop_event = Event()
def randomNumberGenerator():
print("Making random numbers")
while not thread_stop_event.isSet():
with open('savedImage.jpg', 'rb') as f:
image_data = f.read()
socketio.emit('my_response', {'image': image_data}, namespace='/test')
socketio.sleep(2)
#app.route('/')
def index():
return render_template('index.html')
#socketio.on('connect', namespace='/test')
def test_connect():
global thread
print('Client connected')
if not thread.is_alive():
print("Starting Thread")
thread = socketio.start_background_task(randomNumberGenerator)
#socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app)
Using application1.js file to receive the binary form of the image to the client
$(document).ready(function(){
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
var numbers_received = [];
socket.on('my_response', function(msg) {
let arrayBufferView = new Uint8Array(msg['image']);
console.log(arrayBufferView);
var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
//maintain a list of ten numbers
var img_url = URL.createObjectURL(blob);
console.log(img_url);
document.getElementById("img_show").src = img_url;
});
});
And using index.html to show the image, unfortunately nothing is visible
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.min.js"></script>
<script src="static/jscript/application1.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Asynchronous Flask Communication</h1>
<p>Random numbers generated by the Flask server will appear below, asynchronously.</p>
<p>Details <a href='https://www.shanelynn.ie/asynchronous-updates-to-a-webpage-with-flask-and-socket-io/' target='_blank'>here.</a></p>
</div>
</div>
</div>
<div class="container" id="content">
<div class="row">
<h3>Image:</h3>
<div id="img_show">
</div> <!-- /#log -->
</div>
</div>
</body>
</html>

Related

Scala.js webloaded js libraries not present?

I setup a project using scala.js.
At the web part (playframework) I added a static library bxslider.
With scala.js I add a complete new slider (div, ul and li). Without scala.js all works fine, with scala.js the inserted code is not going to be a slider.
I tried to pass a script part with bxSlider() to the correct id. No effect. I get the error bxSlider() is no function.
It seemed to me, that their is no access to bxSlider. Where is the error?
object WidgetSingleArticleSlider {
def articleEntry(x: SharedArticle, addToCartText: String) = {
li(
`class`:="wgsp-item",
a(
href:="#",
figure(
img(src:=x.articleDescription.pictureSeq.headOption.getOrElse(Pictures.emptyPath))
)
),
p(
`class`:="wgsp-title",
a(
href:="#",
x.articleDescription.title
)
),
p(
`class`:="wgsp-price",
(if(x.price.articlePrice(1).specialSubTotal.isDefined)
x.price.articlePrice(1).specialSubTotal.get.formatted("%,.2f ")
else x.price.articlePrice(1).subTotal.formatted("%,.2f ")) + x.price.articlePrice(1).currency
),
div(
`class`:="row no-gutter",
div(
`class`:="col-xs-12 text-center",
a(
`class`:="btn btn-third-col",
href:="#",
addToCartText
),
div(`class`:="gap-30")
)
)
)
}
def toHtml(title: String, articleSeq: Seq[SharedArticle], addToCartText: String) = {
div(
`class`:="widget wg-specials store-alt box-with-pager mobile-collapse",
h3(
`class`:="wg-title mobile-collapse-header store-alt",
title
),
div(
`class`:="wg-body mobile-collapse-body",
ul(
id := "tium",
`class`:="vertical-bx-1",
articleSeq.map(e => articleEntry(e,addToCartText))
)
)
)
}
}
In main.scala.html this is added at the end:
<script src="#routes.Assets.versioned("js/jquery-1.11.0.min.js")"></script>
<script src="#routes.Assets.versioned("js/jquery-ui-1.10.4.custom.min.js")"></script>
#*<script src="#routes.Assets.versioned("plugins/jquery.bxslider.min.js")"></script>*#
<script src="#routes.WebJarAssets.at(webJarAssets.locate("js/jquery.bxslider.js"))"></script>
<script src="#routes.Assets.versioned("js/bootstrap.min.js")"></script>
<script src="#routes.Assets.versioned("js/jquery-accessibleMegaMenu.js")"></script>
<script src="#routes.Assets.versioned("js/jquery.validationEngine.js")"></script>
<script src="#routes.Assets.versioned("js/jquery.validationEngine-en.js")"></script>
<script src="#routes.Assets.versioned("js/fastclick.js")"></script> <!-- Eliminating the 300ms click delay on mobile browsers -->
<script src="#routes.Assets.versioned("js/plugins.js")"></script>
<script src="#routes.Assets.versioned("js/scripts.js")"></script>
#scalajs.html.scripts("client", routes.Assets.versioned(_).toString, name => getClass.getResource(s"/public/$name") != null)
After this their is a request (which works) to scala.js which add the code above to the html structur at main.scala.html.
Now the adding sequence of my scala.js
val child = place.appendChild(Waiting.spinner.render)
Ajax.get(url(s"list/article/random?size=$size"),withCredentials = true).map{ xhr =>
place.removeChild(child)
val articleSeq = upickle.default.read[Seq[SharedArticle]](xhr.responseText)
val box = WidgetSingleArticleSlider.toHtml( title, articleSeq, addToCartText )
place.appendChild( box.render )
}
The problem is, that this added code is not transformed to a bxSlider. Also I try to restart it again as a bxSlider added as a script at WidgetSingleArticleSlider with:
$('.vertical-bx-1').bxSlider({
minSlides: 3,
slideMargin:0,
nextText: '<i class="arrow_carrot-right"></i>',
prevText: '<i class="arrow_carrot-left"></i>',
pager: false,
}));
The result is still only html. Asking for the loaded plugin results in undefined.
This is the code which was added after call:
<div class="widget wg-specials store-alt box-with-pager mobile-collapse"><h3
class="wg-title mobile-collapse-header store-alt">specials</h3>
<div class="wg-body mobile-collapse-body">
<ul id="tium" class="vertical-bx-1">
<li class="wgsp-item"><a href="#">
<figure><img src="/thumbnail/width/200/nothing"></figure>
</a>
<p class="wgsp-title">Wiesenkerbel Saatgut</p>
<p class="wgsp-price">2.34 EUR</p>
<div class="row no-gutter">
<div class="col-xs-12 text-center"><a class="btn btn-third-col" href="#">addToCart</a>
<div class="gap-30"></div>
</div>
</div>
</li>
<li class="wgsp-item"><a href="#">
<figure><img src="/thumbnail/width/200/nothing"></figure>
</a>
<p class="wgsp-title">Vogelmiere Saatgut</p>
<p class="wgsp-price">2.34 EUR</p>
<div class="row no-gutter">
<div class="col-xs-12 text-center"><a class="btn btn-third-col" href="#">addToCart</a>
<div class="gap-30"></div>
</div>
</div>
</li>
</ul>
</div>
<script>
jQuery('#tium').bxSlider();
if (window.jQuery === undefined) window.$ = window.jQuery = jQuery;
$(document).ready(function () {
$('.vertical-bx-1').bxSlider().reloadSlider();
$('#tium').bxSlider().reloadSlider();
$('.vertical-bx').bxSlider({
minSlides: 3,
slideMargin: 0,
nextText: '<i class="arrow_carrot-right"></i>',
prevText: '<i class="arrow_carrot-left"></i>',
pager: false
});
});
</script>
</div>
Solution found. No problem with scala.js it was jquery.
https://github.com/stevenwanderski/bxslider-4/issues/605
var j = jQuery.noConflict();
I added this line to my code and all worked fine.

website on localhost not loading on refresh once the url is updated through window.pushState

My website is not loading on refreshing the page once the url is updated by window.pushState. My website is saved on this location: http://localhost/ajax.test/index.html
but after clicking the link with href="1" the url changes to http://localhost/ajax.test/1
.. here is the source code:
html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<ul>
<li class="list" id="1">home</li>
<li class="list" id="2">project</li>
<li class="list" id="3">about</li>
</ul>
<div id="dynamic"></div>
</body>
</html>
jQuery:
var url = 0;
var state=0;
$(document).ready(function(){
$('ul a').click(function(e) {
e.preventDefault();
alert(e.target);
url = $(this).attr("href");
history.pushState({page:url}, url,url);
loadContent(url);
});
});
$(window).bind('popstate', function(e){
state = event.state;
if(state){
loadContent(state.page);
}else{
loadContent("home");
}
});
function loadContent(currentPage){
alert(currentPage);
$.ajax({
type: "GET",
url: "ajax.php",
data: "id="+currentPage,
success: function(data){
$('#dynamic').html(data);
}
});
};
php:
<?php
$response = $_GET['id'];
if($response=="1")
{
echo "<h1>You loaded HOME</h1>";
}
else if($response=="2")
{
echo "<h1>You loaded PROJECT</h1>";
}
else if($response=="3")
{
echo "<h1>You loaded ABOUT</h1>";
}
?>

html2canvas for html page with multiple images from same source

I have multiple images in an html page.I want to use html2canvas to convert the page to image.The images are local and from same source.It always keep on showing the error msg " Unable to get image data from canvas because the canvas has been tainted by cross-origin data."
The same code will work for one image or multiple copy of same image.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="language" content="de">
<script type="text/javascript" src="./js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/html2canvas.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var target = $('#mainDiv');
html2canvas(target, {
onrendered: function(canvas) {
var data = canvas.toDataURL();
var img = document.getElementById('img1');
img.src = data;
}
});
});
</script>
</head>
<body>
<div id="mainDiv">
<div id="div1" ><p>paragraph 1 paragraph 1 paragraph 1 paragraph 1 paragraph 1 paragraph 1 paragraph 1 paragraph 1 </p></div>
<div id="div2" ><p>paragraph2 paragraph2 paragraph2 paragraph2 paragraph2 paragraph2 paragraph2 paragraph2 </p></div>
<img src="images/01.jpg" >
<img src="images/02.jpg" >
<img src="images/03.jpg" >
<img src="images/04.jpg" >
</div>
<img id="img1"></img>
</body>
</html>
I am not sure what does the error message mean.Also if somebody can tell me how do i make this work with multiple images, it will be very helpful
just remove what you dont need. ie, i have Div1,Div2 etc
function PrintChartCanvas(divId) {
//div canvas
var divObj = html2canvas($('#div' + divId));
var divQueu = divObj.parse();
var divCanvas = divObj.render(divQueu);
divImg = divCanvas.toDataURL();
return divImg;
}
document.getElementById("img1").src = PrintChartCanvas(3);
This should work

Knockoutjs program is not working

I am new to Knockoutjs, starting with http://learn.knockoutjs.com/ tutorial but the same when i am trying in local it is not working.
Do i need to write model and view in separate file or same, My question is how to run first knockout program.
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js'></script>
<script type="text/javascript">
// Here's my data model
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work​​​​​​​​​​​​​​​​​​
</script>
</head>
<body>
<div class='liveExample'>
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span></h2>
</div>​
</body>
</html>
You should put ko.applyBindings to the end of page. Here is a quote from official documentation:
To activate Knockout, add the following line to a block:
ko.applyBindings(myViewModel);
You can either put the script block at the bottom of your HTML
document, or you can put it at the top and wrap the contents in a
DOM-ready handler such as jQuery’s $ function.
So code should look as follow:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js'></script>
</head>
<body>
<div class='liveExample'>
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span></h2>
</div>​
<script type="text/javascript">
// Here's my data model
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work​​​​​​​​​​​​​​​​​​
</script>
</body>
</html>
Here is working fiddle: http://jsfiddle.net/vyshniakov/s2LSE/

DHTMLXScheduler export and import to and from ics doesn't work

I am currently developing a calendar system and I want some events/dates send directly to and ics file from the web calender.
Dhtmlxscheduler is exactly what I need. Writing the data to mysql works and it is reading the data too, but not to ics and from ics.
Here is the code I have so far:
<script src="../../codebase/dhtmlxscheduler.js" type="text/javascript" charset="utf-8"></script>
<script src="../../codebase/ext/dhtmlxscheduler_serialize.js" type="text/javascript" charset="utf-8"></script>
<script src="../../codebase/ext/dhtmlxscheduler_multisource.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="../../codebase/dhtmlxscheduler.css" type="text/css" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8">
function init() {
scheduler.config.xml_date="%Y-%m-%d %H:%i";
scheduler.config.prevent_cache = true;
scheduler.config.lightbox.sections=[
{name:"description", height:130, map_to:"text", type:"textarea" , focus:true},
{name:"location", height:43, type:"textarea", map_to:"details" },
{name:"time", height:72, type:"time", map_to:"auto"}
]
scheduler.config.first_hour=4;
scheduler.locale.labels.section_location="Location";
//scheduler.config.details_on_create=true;
//scheduler.config.details_on_dblclick=true;
scheduler.init('scheduler',new Date(2009,10,1),"month");
scheduler.setLoadMode("month");
scheduler.load(["php/events.php","/ics/schedule.ics"]);
var dp = new dataProcessor("php/events.php");
dp.init(scheduler);
}
function show(){
alert(scheduler.toICal());
}
function save(){
var form = document.forms[0];
form.elements.data.value = scheduler.toICal();
form.submit();
}
function get(){
var form = document.forms[1];
form.elements.data.value = scheduler.toICal();
form.submit();
}
</script>
</head>
<body onload="init();">
<form action="../04_export/php/ical_writer.php" method="post" target="hidden_frame" accept-charset="utf-8">
<input type="hidden" name="data" value="" id="data">
</form>
It would be nice if you could help me. Thanks. Sorry that the post looks a bit strange. It is my first post with code....
Above code loads data from 2 sources in same time, which causes issue as one source is xml based and other is ical data.
scheduler.load(["php/events.php","/ics/schedule.ics"]);
need to be replaced with separate data loading
scheduler.load("php/events.php", "xml")
scheduler.load("ics/schedule.ics", "ical")