I am trying to integrate r to create a very simple web application using DeployR open 8.0.0 on a Ubuntu machine. I am using the following code on the client side:
<html>
<head><script src="./js-client-library-7.4.3/browser/deployr.min.js"></script></head>
<body>
<script>
deployr.configure({cors: true, host: 'http://192.168.0.103:8000'})
var file = document.getElementById('csv-file').files[0]
deployr.auth('testuser','Aniruddha123')
.io('/r/repository/file/upload')
.attach(file, 'defects.csv')
.io('/r/repository/script/execute')
.data({filename: 'forestPredict.R', author: 'testuser', directory: 'root'})
.end(function(result){
ws = result.data.deployr.response.workspace;
var preds = ws.objects[0].value;
var error = ws.objects[1].value;
document.write('<p>'+preds+'</p>'+'ERROR:' error)
})
</script>
</body>
</html>
and the following R code:
.libPaths( c( .libPaths(), "/home/aniruddha/R/x86_64-pc-linux-gnu-library/3.2") )
library(randomForest)
defects = read.csv('defects.csv')
train = defects[is.na(defects$bugs)]
test = defects[!is.na(defects$bugs)]
forestTest = randomForest(bugs~.,train[-1])
preditions = predict(forestTest, test[-1])
test$bugs = round(preditions)
result = rbind(train, test)
trainPreds = predict(forestTest, train[-1])
meanError = mean(abs(train$bugs - trainPreds))
All that I am getting is a button to upload file and thats it...I dont know where I am going wrong...please help.
You can start the log for the deployR and check what actual you are getting using deployr.configure({cors: true, host: 'http://192.168.0.103:8000',logging:true}).
Also, When you click on your upload button, start the developer tools of the browser. You can check where the script is failing.
Related
I want to create a WebApp, that does the following:
User clicks button on WebApp to run script
Get User eMail
Create new Google Spreadsheet (name=eMail)
get Url of that Spreadsheet
Automatically open Url in new Tab
Step 5 is where I am stuck.
I have used window.open(url) before, however that only seems to work when you run code via a Spreadsheet. What I wanna do is displaying the button on my .html and run everything only with the WebApp but I can't do that because I can not use SpreadsheetApp.getUi() from that context.
Is there another way to do this?
Here is the Error im getting:
EDIT: Seems I had some minor mistakes in my Code.gs I think i fixed that now. Still same issue tho
Thank you guys in advance! :)
Here is some sample code:
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("page");
}
function clickEvent () {
const lock = LockService.getScriptLock();
lock.tryLock(5000);
if (lock.hasLock()){
var email = Session.getActiveUser().getEmail();
var url = createFile(email);
openUrl(url); //THIS ONLY WORKED FROM WITHIN SPREADSHEET
lock.releaseLock();
}
}
function createFile(email){
var newSS= SpreadsheetApp.create(email);
var file = DriveApp.getFileById(newSS.getId());
var url = file.getUrl();
return url
}
function openUrl( url ){ //HAS TO CHANGE
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}
}
page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Click Button!</h1>
<button id="btn">Run</button>
<script>
document.getElementById("btn").addEventListener("click",sendRequest);
function sendRequest(){
google.script.run.clickEvent();
}
</script>
</body>
</html>
Get url from app script and open spreadsheet in new tab wit JavaScript
Update app script function
function clickEvent () {
const lock = LockService.getScriptLock();
lock.tryLock(5000);
if (lock.hasLock()){
var email = Session.getActiveUser().getEmail();
lock.releaseLock();
return createFile(email);
}
}
Also update JavaScript Code
function sendRequest(){
google.script.run.withSuccessHandler(
function (link) {
window.open(link, '_blank').focus();
}
).testCSV3();
}
Reference: Communicate with Server Functions
I want to execute a batch file on a button click event from simple HTML page.
In IE, I can use ActiveXObject to achieve this however in other browser ActiveXObject is not supported.
Sample HTML File:
<html>
<head>
<title>Run Batch</title>
<HTA:APPLICATION
APPLICATIONNAME="Run Batch"
ID="MyHTMLapplication"
VERSION="1.0"/>
</head>
<script type="text/javascript">
function RunBat(){
var shell = new ActiveXObject("WScript.Shell");
var path = "D:/Test.bat";
shell.run(path);
}
</script>
</head>
<form>
Execute:
<input type="button" Value="Run" onClick="RunBat();"/>
</form>
</html>
I have gone through many questions on different forums and what I have found is that, in other browsers it is possible through some add-ons.
Is there any other way to execute it without using any add-ons in other browser?
If no, what are the add-ons I can use for Firefox, Chrome and Edge browsers to achieve this?
Due to security reasons it's not possible to launch user files (as batch scripts) from the web browser. This is unless you're trying to develope an electron app, which i think you could see, in that case try this code:
(REQUIRES NODE.JS INTEGRATION)
"use strict";
var myBatFilePath = "C:\\Path\\To\\User\\s\\file.bat";
const spawn = require('child_process').spawn;
var bat = spawn('cmd.exe', ['/c', myBatFilePath]);
bat.stdout.on('data', (data) => {
//Logs the batch's echos to the console
var str = String.fromCharCode.apply(null, data);
console.info(str);
});
bat.stderr.on('data', (data) => {
//Logs as error the batch's echos that end with "1>&2"
var str = String.fromCharCode.apply(null, data);
console.error(str);
});
bat.on('exit', (code) => {
//Handles batch exit codes
var preText = `Child exited with code ${code} : `;
switch(code){
case 0:
console.info(preText); // EXIT CODE 0 (no exit code provided)
break;
case 1:
console.info(preText); // EXIT CODE 1
break;
case 2:
console.info(preText); // EXIT CODE 2
break;
case 3:
console.info(preText); // EXIT CODE 3
break;
//AND SO ON
}
});
I'm trying to use this library to implement a tracking pixel.
I'm testing in my localhost machine with Apache.
I have a index.html page at htdocs/openpixel/index.html
with the following content:
<html>
<head>
Test Pixel
</head>
<body>
Test Pixel
<!-- Start Open Pixel Snippet -->
<script>
!function(e,t,n,p,o,i,a,s,c){e[o]||(a=e[o]=function(){a.process?a.process.apply(a,arguments):a.queue.push(arguments)},a.queue=[],a.t=1*new Date,s=t.createElement(n),s.async=1,s.src=p+"?t="+Math.ceil(new Date/i)*i,c=t.getElementsByTagName(n)[0],c.parentNode.insertBefore(s,c))}(window,document,"script","http://127.0.0.1/openpixel/v1/openpixel.js","opix",864e5),opix("init","ID-123"),opix("event","pageload");
</script>
<!-- End Open Pixel Snippet -->
</body>
</html>
This is openpixel.js, where it should send the data to an endpoint
...
window.onload = function () {
var aTags = document.getElementsByTagName('a');
for (var i = 0, l = aTags.length; i < l; i++) {
aTags[i].onclick = function (e) {
if (Url.externalHost(this)) {
Config.externalHost = { link: this.href, time: now() };
}
}.bind(aTags[i]);
}
};
}(window, document, window["opix"], "opix", "http://localhost:3000/pixel_data", 1));
...
I also created an endpoint api in Node.JS to receive this pixel. When I test it with a browser get resquest it is responding.
app.get('/pixel_data', function(req, res) {
console.log(req.query);
});
The problem is when I access pixel.html, the endpoint /pixel_data is logging nothing. I'm trying to understand the problem here.
You're Node.js server is not able to see the query string because it looks like your server is on localhost:3000 and you are sending a request to 127.0.0.1/openpixel/v1/openpixel.js.
Change your pixel tag to request localhost:3000 by changing http://127.0.0.1/openpixel/v1/openpixel.js to http://localhost:3000/pixel_data.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function(){
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');
var iNow = 1;
oInput.onclick = function(){
var number = randomNum(35,7);
oDiv.innerHTML = number;
history.pushState(number,'');
}
window.onpopstate = function(event){
var number = event.state || '';
oDiv.innerHTML = number;
}
function randomNum(alls,now){
var arr = [];
var newArr = [];
for(var i=1;i<=alls;i++){
arr.push(i);
}
for(var i=0;i<now;i++){
newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
}
return newArr;
}
}
</script>
</head>
<body>
<input type="button" id="input1" value="35選7" />
<div id="div1"></div>
</body>
I don't know why history.pushState does not work, it throws the error:
history.html:14 Uncaught SecurityError: Failed to execute 'pushState' on
'History': A history state object with URL
'file:///C:/Users/TED/Documents/HBuilderProjects/javascript-%E7%9F%A5%E8%AD%98%E9%A1%9E/history.html' cannot be created in a document
with origin 'null' and URL
'file:///C:/Users/TED/Documents/HBuilderProjects/javascript-%E7%9F%A5%E8%AD%98%E9%A1%9E/history.html'.oInput.onclick # history.html:14
Don't pretend that file:/// is the same as "web pages": they didn't get loaded by the browser using the same mechanism that real web pages go through, and lots of things that web pages can do will not work for "plain files".
If you want to see how your code behaves as web page, using web APIs, then you'll need to load it properly using http(s). That means using a simple server (not even a full blow Apache or the like, just a one-liner http server like python -m SimpleHTTPServer, or php -S localhost:8000 or node.js's http-server or live-server packages, etc. etc.) and then load it through http://localhost:someport/yourfilename, where "someport" is whatever port number the one-line server says is being used, and "yourfilename" is obviously the name of your file.
I am relatively new to JavaScript and subsequently Node + Express.IO. I am trying to build a page that will track in real time connections made by different 'users' to the server. Consequently, when I do include all the functions from the io module, my prompt() and alert do not work anymore. I am running nodemon app.js from my terminal and no compilation errors are showing up when I do so. The alert and prompt work again when I remove all the io functions.
These are the contents of my index.ejs <body> tag:
<body>
<h1>Chatroom</h1>
<script>
alert("Hello!");
var name = prompt("What is your name?");
io.connect();
io.emit.('got_a_new_user', {name: name});
io.on('new_user', function(data) {
//render this new info in the HTML
var users = data.users;
console.log(users);
if (users != undefined) {
console.log("\n\n\n" + users);
// if users is defined, append the new division containing the username
}
});
io.on('disconnect_user', function(data) {
var users = data.users;
if (users != undefined) {
// If users is defined remove the corresponding HTML element
}
});
</script>
<div id="container">
</div>
</body>
Any help would be much appreciated.
Adding example for the comment added by UKatz,
You will have to connect socket.io from the client as follows,
index.ejs
<script src="http://ip:port/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://ip:port');
socket.emit('got_a_new_user', {name: name});
</script>
Check socket.io documentation for how to connect socket.io with client.