phantomjs SVG server response - d3.js

I've a phantomjs server which loads a page do some d3 visualization. I was able to do the visualization things work but my problem is how to write the final html to response. My code is below.
// server.js
service = server.listen(8124, function (request, response) {
console.log('Request received at ' + new Date());
response.statusCode = 200;
response.headers = {
'Cache': 'no-cache',
'Content-Type': 'text/plain;charset=utf-8',
'Content': ''
};
var req = JSON.parse(request.post);
visualize();
response.write(??) //
});
// app.js
var webPage = require('webpage');
var page = webPage.create();
function visualize() {
page.open("./index.html", function() {
var ret = page.evaluate(function() {
// Do some SVG work
});
console.log(ret); // <svg><g></g></svg
// at this point I am sure that the ret is an html svg element. How can I write this to response?
});
}

Related

Nodejs - xmlhttprequest promise never finish

module.js
var Promise = require('bluebird');
var XMLHttpRequest = require('xhr2');
function fetchdata(id) {
var url = 'http://www.youtube.com/watch?v=' + id;
return new Promise(function (fulfill, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
var jsonStr;
try {
fulfill(xhr.response);
} catch (e) {
reject(jsonStr);
}
};
xhr.onerror = function(e) {
reject(e);
};
xhr.send('');
});
}
module.exports = {
getdata: function (videoID) {
return new Promise(function (fulfill, reject) {
if (!videoID) {
reject(new Error('Unable to get video id.'));
return;
}
fetchdata(videoID).then(
function (d) {
console.log( d);
}
);
});
}
};
index.js
var parser = require('./module.js');
parser.getdata("ZI4tRn4dOGg", function (data) {
console.log(data);
}
)
I tried to get youtube view page source code with xmlhttprequest.
BUT above code does not finish. I guess it is waiting for something.
Is problem from bluebird? or xhr2? and why does this code never finish?
Your xhr instance had a memory leak, might be a problem with the library, last publish was a year ago. Bluebird was ok. You can fix the hangup by using node-fetch and dropping in this replacement for fetchdata
const fetch = require('node-fetch')
function fetchdata(id) {
var url = 'http://www.youtube.com/watch?v=' + id;
return fetch(url).then(res => res.text())
}

How can I use NativeScript 3 to capture image and send to a remote server

I'm new to NativeScript and I'm trying to capture an image with the camera module (this works fine), and convert it to base64 (this is not working) and POST to server.
I've googled for days. Any help you can lend would be immensely appreciated.
I've tried this about 16 billion different ways and this is my current code:
viewModel.takePicture1 = function() {
camera.requestPermissions();
var isAvailable = camera.isAvailable();
console.log(isAvailable);
var options = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture().then(function (img) {
try{
var imageData = img.toBase64String("jpeg"); // fails here
console.log(imageData);
}catch(err){
console.log("Error: "+err);
}
http.request({
url: "http://[server address]/lab/ns_exp/upload_test.php",
method: "POST",
headers: { "Content-Type": "application/base64" },
content: imageData
}).then(function() {
console.log("Upload successful");
}).catch(function(e) {
console.log("Unsuccessful upload", e);
});
});
}//
Oh, I do want to make clear that I'm not using angular (obviously), so please don't provide an answer that does so. : ) (Vuejs Holdout)
The key here is that base64 needs to know that the image is a JPEG, and what quality the image should be. The code should look like this:
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
Just in case someone finds this later and wonders about putting the image (UI) and/or the image (base64) into an observableArray, here is my complete function:
viewModel.takePhoto = function(){
var self = this;
camera.requestPermissions();
var cameraOptions = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
self.photoData.push({"data": base64});
var image = new imageModule.Image();
image.src = imageAsset;
self.photoUI.push({"src": image.src});
listView.refresh();
})
}).catch(function (err) {
console.log("Error -> " + err.message);
});
}

Pass image through ajax using cordova

I am developing my mobile application using ionic framework and I want it to connect to my API through ajax. Currenty, in the mobile side, which is I am using Ionic Framework, I want to upload an image and pass it to my api through ajax. I am using Cordova for the upload but it seems it doesn't found the URL I indicated.
Here's the HTML
<ion-footer-bar class="bar bar-positive">
<div class="button-bar">
<button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="image === null">Upload</button>
</div>
</ion-footer-bar>
Here's the uploadImage() function in the controller (Just copied the code in a site. Forgot where) EDIT: added targetPath
$scope.uploadImage = function() {
// Destination URL
var url = "http://192.168.0.19/identificare_api/public/api/plants/image";
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
var jsonparse = JSON.parse(result);
$scope.showAlert(jsonparse);
}
But in the upload part, I want to do it in ajax to indicate the method for the URL but the problem I don't know what put in data.
$.ajax({
url: "http://192.168.0.19/identificare_api/public/api/plants/image",
type: 'POST',
data:
success:function(json){
var jsonparse = JSON.parse(json);
alert(jsonparse);
},
error:function(){
alert("Error");
}
});
Can someone help me with this issue?
UPDATE: Applied here #Blauharley's comment below
I had another issue here. I returned the $_FILES['image']['tmp_name'] in the API side but it returns nothing but when I returned the $_FILES['image']['name'], it returned my_image.jpg. Why it doesn't have tmp_name?
$scope.uploadImage = function() {
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
$scope.getBase64ImageByURL(targetPath).then(function(base64Image){
var blob = $scope.base64ToBlob(base64Image,'image/jpeg');
var fd = new FormData();
fd.append('image', blob, "my_image.jpg");
fd.append('user_token', "rLUrh37rfTozuBxmemHtlKMgH");
$.ajax({
url: 'http://192.168.0.19/identificare_api/public/api/plants/image',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success:function(res){
alert(res);
},
error:function(err){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
};
$scope.getBase64ImageByURL = function(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
dfd.resolve(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
};
$scope.base64ToBlob = function(base64Image,toMimeType) {
var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: toMimeType
});
return blob;
};
ADDED: API side
public function image(){
echo json_encode($_FILES['image']['tmp_name']);
}

BeagleBone Black sending data to a web server using BoneScript

How do I send data (via ajax post or get) from BeagleBone Black to a web server using BoneScript?
As I understand, XMLHttpRequest does not exist. Is there another approach?
I found the solution: In fact, I see this operation is not related to beaglebone. It relates to nodejs. So, the key is require('http') by node.
var http = require('http');
http.get('http://www.example.com', function(response) {
var response_data = '';
response.on('data', function(chunk) {
response_data += chunk;
})
.on('end', function() {
console.log(response_data);
})
.on('error', function(e) {
console.log('Error: ' + e.message);
});
});
OR if you want to do that simpler, you can use Requistify
npm install requestify
After installed you can use it like:
var requestify = require('requestify');
// GET Example
requestify.get('http://example.com').then(function(response) {
// Get the response body (JSON parsed - JSON response or jQuery object in case of XML response)
response.getBody();
// Get the response raw body
response.body;
});
// POST example
requestify.post('http://example.com', {
hello: 'world'
})
.then(function(response) {
// Get the response body
response.getBody();
});

embed webgl in powerpoint or render animated gif from webgl

anyone got an idea how to embed a webgl animation into powerpoint. any tools that can be used on server side to capture an animated gif?
I did not make it work to embed webgl html directly in a powerpoint.
You can create images of webgl by calling toDataURL() as in
var canvas = document.createElement("canvas");
var gl = canvas.getContext("experimental-webgl");
function render() {
gl.clearColor(Math.random(), Math.random(), Math.random(), 1);
gl.clear(gl.COLOR_BUFFER_BIT);
// takes a 'screenshot' of the canvas.
var image = canvas.toDataURL();
requestAnimationFrame(render);
}
render();
To make an animation you could send each of those screenshots to a server
...
var image = canvas.toDataURL();
var req = new XMLHTTPRequest();
req.open("POST", "http://localhost:8080", true);
var data = {
cmd: 'screenshot',
dataURL: image,
};
req.setRequestHeader("Content-type", "application/json");
req.send(JSON.stringify(data));
Here's a node.js server that will save the screenshots as .png files. You could then load them into some program to turn them into a gif.
var port = 8080
var screenshotCount = 0;
var http = require('http'),
url = require('url'),
fs = require('fs'),
util = require('util'),
path = require('path'),
querystring = require('querystring');
function postHandler(request, callback) {
var query_ = { };
var content_ = '';
request.addListener('data', function(chunk) {
content_ += chunk;
});
request.addListener('end', function() {
query_ = JSON.parse(content_);
callback(query_);
});
}
function sendJSONResponse(res, object) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(object), 'utf8');
res.end();
}
function startsWith(str, start) {
return (str.length >= start.length &&
str.substr(0, start.length) == start);
}
function saveScreenshotFromDataURL(dataURL) {
var EXPECTED_HEADER = "data:image/png;base64,";
if (startsWith(dataURL, EXPECTED_HEADER)) {
var filename = "screenshot-" + (screenshotCount++) + ".png";
fs.writeFile(
filename,
dataURL.substr(
EXPECTED_HEADER.length,
dataURL.length - EXPECTED_HEADER.length),
'base64');
util.print("Saved Screenshot: " + filename + "\n");
}
}
server = http.createServer(function(req, res) {
// your normal server code
if (req.method == "POST") {
postHandler(req, function(query) {
switch (query.cmd) {
case 'screenshot':
saveScreenshotFromDataURL(query.dataURL);
sendJSONResponse(res, { ok: true });
break;
default:
util.print("err: unknown post: " + query + "\n");
break;
}
});
}
}),
server.listen(port);
Note that server only saves screenshots, it doesn't serve files (for brevity). So you'll need to either add that functionality or serve the files from another server.

Resources