I've managed to run the following code thanks to this post here Adding Microsoft's Emotion API to HTML website.
<HTML>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key-here");
},
type: "POST",
// Request body
data: '{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}',
})
.done(function(data) {
alert("success");
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
</body>
</head>
</html>
This may seem like stupid question however I've been wondering how to get the emotions output from the HTML file? i.e. instead of the success alert I'd like to generate a text file which shows the output of the Emotions API with each emotion (like it does on their website).
One solution could be to read about Blob's. You could take the response from the ajax call in done() and create the text file you need. Here is an example for using Blob I found on JSFiddle:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
source
data is an array, one item per face. If you just want to dump the text, you can call JSON.stringify(data). If you want pretty-print it in HTML, take a look at How can I pretty-print JSON using JavaScript?.
I've done this ins my website HowHappy.co.uk which is also on GitHub here: https://github.com/martinkearn/How-Happy
The way I displayed the data in a web site was to enumerate the array of faces in Javascript and use basic CSS to show the rectangle in the right place and Bootstrap popover to show the details data.
There is too much to put in this response so I recommend you look though the GitHub repo, but here are some of the key bits
Javascript
var dataString = JSON.stringify(response);
var data = JSON.parse(dataString);
//draw rectangle for each face
$.each(data.Faces, function (index, value) {
var rect = document.createElement('div');
rect.className = "rect";
rect.style.height = value.faceRectangle.height + "px";
rect.style.width = value.faceRectangle.width + "px";
rect.style.left = value.faceRectangle.left + "px";
rect.style.top = value.faceRectangle.top + "px";
rect.id = "rect" + index;
$('#result').append(rect);
//add popover
var popoverBody = "Happiness: " + Number((value.scores.happiness).toFixed(2))
+ "<br>Fear: " + Number((value.scores.fear).toFixed(2))
+ "<br>Anger: " + Number((value.scores.anger).toFixed(2))
+ "<br>Contempt: " + Number((value.scores.contempt).toFixed(2))
+ "<br>Disgust: " + Number((value.scores.disgust).toFixed(2))
+ "<br>Neutral: " + Number((value.scores.neutral).toFixed(2))
+ "<br>Sadness: " + Number((value.scores.sadness).toFixed(2))
+ "<br>Surprise: " + Number((value.scores.surprise).toFixed(2));
$('#rect' + index).popover({
title: (index + 1)
content: popoverBody,
html: "true",
trigger: "click"
});
});
Css
.rect {
position: absolute;
border-color: #FFEA0E;
border-style: solid;
border-width: 4px;
z-index: 10;
}
#result {
position: relative;
text-align: center;
margin: 0 auto;
width: auto;
}
#resultDetails {
font-size: 3rem;
text-align: center;
}
Related
I'm testing Prebid on mobile devices. In my AdUnit, I have defined dimensions as follows:
Prebid parameters
But, I get ads with different dimensions:
Prebid sizes
It seems to me that advertisers don't understand that the ad is displayed on a mobile device, maybe that's the problem. Maybe there is a parameter I forgot.
I played my auctions in an iFrame, maybe that's the problem.
I use 4.25 version.
Please tell me if my post is incorrect or incomplete, it's my first post on stackoverflow.
Thank a lot for your help.
The problem is solved. You can see details here: https://github.com/prebid/Prebid.js/issues/6307.
If you use ImproveDigital adapter just add improvedigital: {usePrebidSizes: true} in pbjs.setConfig
pbjs.setConfig({ improvedigital: {usePrebidSizes: true} });
My full sample here :
The HTML page :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="testmobile.js"></script>
</head>
<body>
<div id="b48fef10-6f72-4f83-9a91-77c42069bd87">
</div>
</body>
</html>
The javascript code :
/** add your prebid dll here or in html file **/
let adUnits = [];
let adUnit =
{
code: "b48fef10-6f72-4f83-9a91-77c42069bd87",
mediaTypes: {
banner: {
sizes: [[300,100],[320,100],[320,50],[300,50]]
}
},
bids: [
{
bidder:"onetag",
params:{
pubId:"xxxxxxxxxxxxxxxxx"
}
},
{
bidder:"appnexus",
params:
{
placementId:"xxxxxxxxxxxxxxxxx"
}
},
{
bidder:"improvedigital",
params:
{
placementId:"xxxxxxxxxxxxxxxxx"
}
}]
};
adUnits.push(adUnit);
pbjs.que.push(function () {
pbjs.setConfig({
debug: true,
improvedigital: {usePrebidSizes: true}
});
pbjs.addAdUnits(adUnits);
pbjs.requestBids({
bidsBackHandler: function (bidResponses) {
var winningBids = [];
let ad = pbjs.getHighestCpmBids("b48fef10-6f72-4f83-9a91-77c42069bd87");
if (ad && ad.length > 0) {
let idIFrame = "b48fef10-6f72-4f83-9a91-77c42069bd87frame";
let iFrame = "<iframe id='" + idIFrame + "'"
+ " FRAMEBORDER=\"0\""
+ " SCROLLING=\"no\""
+ " MARGINHEIGHT=\"0\""
+ " MARGINWIDTH=\"0\""
+ " TOPMARGIN=\"0\""
+ " LEFTMARGIN=\"0\""
+ " ALLOWTRANSPARENCY=\"true\""
+ " WIDTH=\"0\""
+ " HEIGHT=\"0\">."
+ " </iframe>"
document.body.innerHTML += '<div id=b48fef10-6f72-4f83-9a91-77c42069bd87>' + iFrame + '</div>';
var iframe = document.getElementById(idIFrame);
var iframeDoc = iframe.contentWindow.document;
try {
pbjs.renderAd(iframeDoc, ad[0]['adId']);
} catch (e) {
console.log(e);
}
winningBids = pbjs.getAllWinningBids();
console.log(winningBids);
}
else
{
console.log("No bids");
};
},
timeout: 2000
});
});
I know, there are hundreds of questions on this topic on here, but I still could not find satisfactory answers after a day of searching:
I have a 2D javascript array, which I want to download as an Excel sheet.
Here is a fiddle with the code I got so far:
https://jsfiddle.net/3an24jmw/7/
The download works, but there are several issues, which I could not solve after days of trying:
All items end up in the first column of the Excel sheet, because Excel interprets the "," separating the elements as part of the data. How can I separate the elements in a way Excel understands?
The file name is some cryptic code. How can I set the file name?
The downloaded file has a double .xls ending (.xls.xls). How can get a single .xls ending?
Excel tells me every time the file could be corrupted or unsafe. How do I prevent this?
Any help for any of these questions would be appreciated.
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(CsvString));
}
UPDATE
I just found out by chance, that 1. 2. and 4. can be solved by replacing vnd.ms-excel with csv.
The file will not be .xls anymore, but the csv can be opened by Excel without problems and behaves like intended.
Only problem remaining is the file name!
UPDATE 2
Finally after 2 full workdays of searching and trying, I found the solution, which I would like to share here, to help anybody with the same problem:
Simply include an invisible <a> element, which defines the file an useful name using its download="somedata.csv" attribute.
Here is my final and fully functional fiddle:
https://jsfiddle.net/3an24jmw/25/
Finaly after 2 full workdays of searching and trying, I found the solution, which I would like to share here, to help anybody with the same problem:
Simply include an invisible element, which gives the file an usefull name using its download="somedata.csv" attribute:
Here is my final and fully functional fiddle:
https://jsfiddle.net/3an24jmw/25/
var Results = [
["Col1", "Col2", "Col3", "Col4"],
["Data", 50, 100, 500],
["Data", -100, 20, 100],
];
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
CsvString = "data:application/csv," + encodeURIComponent(CsvString);
var x = document.createElement("A");
x.setAttribute("href", CsvString );
x.setAttribute("download","somedata.csv");
document.body.appendChild(x);
x.click();
}
The separator Excel expects for csv depends on your system locale setting for list separator.
You can hint Excel which separator to use for your csv file by adding "sep=," as the first line.
In your case use could use: var CsvString = '"sep=,"\r\n';
https://github.com/shuchkin/simplexlsxgen#js-array-to-excel-ajax
<?php // array2excel.php
if (isset($_POST['array2excel'])) {
require __DIR__.'/simplexlsxgen/src/SimpleXLSXGen.php';
$data = json_decode($_POST['array2excel'], false);
\Shuchkin\SimpleXLSXGen::fromArray($data)->downloadAs('file.xlsx');
return;
}
?>
<html lang="en">
<head>
<title>JS array to Excel</title>
</head>
<script>
function array2excel() {
var books = [
["ISBN", "title", "author", "publisher", "ctry"],
[618260307, "The Hobbit", "J. R. R. Tolkien", "Houghton Mifflin", "USA"],
[908606664, "Slinky Malinki", "Lynley Dodd", "Mallinson Rendel", "NZ"]
];
var json = JSON.stringify(books);
var request = new XMLHttpRequest();
request.onload = function () {
if (this.status === 200) {
var file = new Blob([this.response], {type: this.getResponseHeader('Content-Type')});
var fileURL = URL.createObjectURL(file);
var filename = "", m;
var disposition = this.getResponseHeader('Content-Disposition');
if (disposition && (m = /"([^"]+)"/.exec(disposition)) !== null) {
filename = m[1];
}
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = fileURL;
} else {
a.href = fileURL;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
alert("Error: " + this.status + " " + this.statusText);
}
}
request.open('POST', "array2excel.php");
request.responseType = "blob";
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("array2excel=" + encodeURIComponent(json));
}
</script>
<body>
<input type="button" onclick="array2excel()" value="array2excel" />
</body>
</html>
Hello everyone I've tried everything I can think of to make this work. I know it does return stream = null or active through use in the browser, but It will not apply my buttons to my page. Not so good with javascript can anyone point me in the right direction.
<script type="text/javascript">
(function() {
var user_name, api_key;
user_name = "Undead_Atomsk";
api_key = "************************";
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.write(Live!);
} else {
document.write(Offline!);
}
});
})();
</script
Took your advice and used browser tools "Completely forgot about those".
I added this line to my html.
I then made a .js file and used the following code everything works now the twitch API is just slow!
(function() {
var user_name, api_key, twitch_widget;
user_name = "Undead_Atomsk";
api_key = "********************";
twitch_widget = $("#twitch-widget");
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.getElementById("twitch-btn").innerHTML = 'Live!';
} else {
document.getElementById("twitch-btn").innerHTML = 'Offline!';
}
});
})();
I use the library Highcharts in order to generate some graphics.
I would like to send them to the server and also to do a mysql request in order to save the data informations into my database. The thing is that It just download the file into my compuer.
I really would like to keep it on the server on a predefined folder. It just dowload it.
I wrote this code with many efforts.
I met many problems but I don't know how to pass this last.
Here is the code for generating the image and to download it auomatically:
<script type="text/javascript">//<![CDATA[
$(function(){
/**
* Create a global getSVG method that takes an array of charts as an argument
*/
Highcharts.getSVG = function(charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ');
svg = svg.replace('</svg>', '</g>');
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="2400px" width="1200px" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
/**
* Create a global exportCharts method that takes an array of charts as an argument,
* and exporting options as the second argument
*/
Highcharts.exportCharts = function(charts, options) {
var form
svg = Highcharts.getSVG(charts);
// merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// create the form
form = Highcharts.createElement('form', {
method: 'post',
action: options.url
}, {
display: 'none'
}, document.body);
// add the values
Highcharts.each(['filename', 'type', 'width', 'svg'], function(name) {
Highcharts.createElement('input', {
type: 'hidden',
name: name,
value: {
filename: options.filename || 'chart',
type: options.type,
width: 1200,
svg: svg
}[name]
}, null, form);
});
//console.log(svg); return;
// submit
form.submit();
// clean up
form.parentNode.removeChild(form);
};
$('#export').click(function() {
Highcharts.exportCharts([chart1, chart2, chart3]);
});
});//]]>
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script type="text/javascript" src="http://highcharts.com/js/testing-exporting.js"></script>
<div id="container" style="height: 400px; width:1200px"></div>
<div id="container2" style="height: 400px; width:1200px"></div>
<div id="container3" style="height: 400px; width:1200px"></div>
<button id="export">Export all</button>
I just try to send it to to server.
Thank you all verry much in advance for the help.
Receive my Utmost Respect.
Kind Regards SP.
you can try this
var chart = $('#yourchart').highcharts();
svg = chart.getSVG();
var base_image = new Image();
svg = "data:image/svg+xml,"+svg;
base_image.src = svg;
$('#mock').attr('src', svg);
var dataString = $('#mock').html() ; // or just binary code
$.ajax({
type: 'POST',
data: dataString,
url: 'your-server/',
success: function(data){
}
});
Save highchart as binary image
I am working on some jquery stuff and ran into this error and I can't figure out how to fix it. I am using the flickr api to view the top 16 photos of the day, and I am doing so using the javascript canvas, but it keeps giving me that error. Here is my code.
var URLs = new Array();
function draw() {
// Loop through all images
var ctx = $('#canvas')[0].getContext("2d");
for (i=0;i<16;i++){
//document.write(URLs[i]);
//alert("hi");
ctx.drawImage(URLs[i],i * 120,i*120,100,100);
}
}
$.ajax({
url: 'http://api.flickr.com/services/rest/?&method=flickr.interestingness.getList&api_key=40ebfc18056e62c7e1cbec778b1db727&format=json&jsoncallback=?',
dataType: "jsonp",
success:function(data){
for(var i = 0; i < 16; i++)
{
var photoURL = 'http://farm' + data.photos.photo[i].farm + '.static.flickr.com/' + data.photos.photo[i].server + '/' + data.photos.photo[i].id + '_' + data.photos.photo[i].secret + '_m.jpg';
URLs[i] = photoURL;
}
draw();
}
})
and
<html>
<head>
<title>Flickr Art gallery</title>
<script src="/js/jquery.js"></script>
<script src="/js/flickr.js"></script>
<style type="text/css">
img { display:none; }
table { margin: 0 auto; }
td { padding:15px; }
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="600"></canvas>
</body>
</html>
The error is happening because of the canvas, when I call drawImage, it throws this, so I was wondering what would cause that. Thanks in advance.
The error was :
Uncaught TypeError: Type error
d.d.extend._Deferred.f.resolveWith jquery.js:16
v jquery.js:16
d.ajaxTransport.send.d.onload.d.onreadystatechange jquery.js:16
The drawImage method wants an Image object, not a string. So, you just need to instantiate your URLs as Image objects:
for(i = 0; i < 16; i++) {
var image = Image.new();
image.src = URLS[i];
ctx.drawImage(image, i * 120, i * 120, 100, 100);
}
The "Type Error" part of your error message is clear enough once you know what drawImage wants. The rest of the error message is a bit of a mess because the exception originates inside a function that is being called by jQuery's AJAX success callback, this means that you end up with several layers of obscurity between you and and your bug.