running a csv input API and connecting to a zoomable sunburst API - html

I hope you are having a nice day.
I am trying to use this CSV input API -- https://github.com/MounirMesselmeni/html-fileapi -- to populate the data array in this zoomable sunburst API:https://plotly.com/javascript/plotlyjs-function-reference/.
Currently, I am able to load in the CSV to the API, and the contents will show on the screen. However, the data is not connecting to the Data Visualization API Script. I am very confused as to why it is not.
See the picture here -- [1]: https://i.stack.imgur.com/oQeY2.png
Currently, the computer is saying there is a "Unexpected end of input" at the final which the Data visualization API is contained within.
It won't even reach the console.log("hello") statement within the script :,(
The code looks like this:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>CSV to Zoomable Sunburs</title>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div>
<form class="form-horizontal well">
<legend>
<h3>
<div id="title">HTML5 File API</div>
</h3>
</legend>
<fieldset>
<label for="csvFileInput"> <strong>CSV File:</strong>
</label>
<input type="file" id="csvFileInput" onchange="handleFiles(this.files)" accept=".csv">
</div>
</fieldset>
</form>
<div id="output">
</div>
</div>
<div id='myDiv'>
<!-- Plotly chart will be drawn inside this DIV -->
</div>
<script type="text/javascript" src="read-csv.js"></script>
</body>
<script>
lines = FileReader.readAsText(Blob|File, opt_encoding);
console.log("hello");
pieces = [];
tempData = [];
(also just to note tempData should hold all of the pieces of the data and then pieces will be used to populate the data array later more easily)
while (typeof lines[0] !== "undefined") {
var line = lines.shift();
var split = line.split(',');
console.log("this is the line: " + line);
console.log("this is the split: " + split);
tempData.push(split);
document.querySelector("#content").innerHTML += split[0] + "<br/>";
}
// iterate through the temp data file
for (let i = 0; i < tempData.length; i += 1) {
const currentKey = tempData[i];
const currItem = calendarE[currentKey];
if (i == 0) { // type
pieces[0] = tempData[0];
}
which then populates the data array as such:
var data = [{
type: pieces[0],
labels: pieces[1],
parents: pieces[2],
outsidetextfont: { size: pieces[3], color: pieces[4], },
leaf: { opacity: pieces[5], },
marker: { line: { width: pieces[6], } },
}];
and then ends as such:
Plotly.newPlot('myDiv', data, layout);
</script>
</html>
Any help as to why I am not getting any console.log statements from inside the data visualization script would be AWESOME thank you so so much!!

Related

Second HTML from Google doc crashes layout

In my Google Application Script web I am loading dynamically Google Doc as HTML. If I insert second HTML exactly the same way then it crashes the layout.
You can test it here
Test scenario 1
Load page
wait till see the text (file 1 is loaded)
go to the other tab and load file2
go back to the first tab and the layout is different (the error is not consistent in terms when and how it performs)
Test scenario 2
Load page
wait till see the text (file 1 is loaded)
load file 3
check the bottom of the page. New test appears and everything is ok
Test scenario 3
Load page
wait till see the text (file 1 is loaded)
load file 3
check the bottom of the page. New test appears and everything is ok
go to the other tab and load file2
go back to the first tab and the layout is different (the error is not consistent in terms when and how it performs)
Server side code looks like. NOTE that from file3 are removed <head> tags.
Could someone explain and hopefully suggest a solution to this issue?
function doGet() {
return HtmlService.createHtmlOutputFromFile("index");
}
function getGoogleDocumentAsHTML(file){
console.log(file)
if (file == 1){
var docID ="1vRMY6bIkUc_J6qDOUJszIYAtIWH-aHTdYYgCmlL4"
}
if (file == 2 || file == 3){
var docID ="1VBpazC3SO2hx4PA7r3A2jud5O9-teNu0nvvnIDac"
}
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docID+"&exportFormat=html&format=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText()
// return cleanHTML(html)
if (file == 3 ){
return cleanHTML(html)
}
return html
//return HtmlService.createHtmlOutput(html).getContent()
}
function cleanHTML(html){
// nuke the whole head section, including the stylesheet and meta tag
html = html.replace(/<head>.*<\/head>/, '');
// remove almost all html attributes
// html = html.replace(/ (id|style|start|colspan|rowspan)="[^"]*"/g, '');
// html = html.replace(/ (id|class|style|start|colspan|rowspan)="[^"]*"/g, '');
// remove all of the spans, as well as the outer html and body
// html = html.replace(/<(span|\/span|body|\/body|html|\/html)>/g, '');
// clearly the superior way of denoting line breaks
// html = html.replace(/<br>/g, '<br />');
return html
}
and html part is here
<!DOCTYPE html>
<html>
<head>
<base target="_self">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" media="screen,projection" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.9.3/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.9.3/js/tabulator.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.9.3/css/materialize/tabulator_materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
<body>
<div class="row">
<div class="col s12">
<ul class="tabs" id="tabsTest">
<li class="tab col s3">HTML from file - loaded</li>
<li class="tab col s3">Second to be loaded</li>
</ul>
</div>
<div id="test1" class="col s12">
<button id ="testingAdmin" class="waves-effect btn" onClick="getHTML(2)">Load second HTML</button>
<div id="test" class="container col s12"> </div>
</div>
<div id="test2" class="col s12">
<button id ="testingAdmin" class="waves-effect btn" onClick="getHTML(3)">Load third HTML</button>
<div id="testovani" class="container col s12"></div>
<div id="test3" class="container col s12"> </div>
</div>
<script>
function getHTML(file){
google.script.run.withSuccessHandler(
function(output){
if (file == 1){
document.getElementById("testovani").innerHTML = output
}
if (file == 2){
document.getElementById("test").innerHTML = output
}
if (file == 3){
document.getElementById("test3").innerHTML = output
}
}
).getGoogleDocumentAsHTML(file);
}
document.addEventListener("DOMContentLoaded", function(event) {
var options ={}
var tabs = document.querySelectorAll('.tabs')
var tabsOptions = {
onShow : function(e) {
console.log(e.id)
switch (e.id){
case "test2":
console.log("testing")
break;
default:
}
}
}
var instance = M.Tabs.init(tabs, options);
getHTML(1)
});
</script>
</body>
</html>

Convert Remote HTML tempalte to PDF in django

I am trying to convert HTML(hosted on a remote server) to pdf and then save in the Django model.
what I tried till now.
def convert_html_to_pdf(template, context, filename):
response = requests.get(template)
template = Template(response.content)
html = template.render(Context(context))
f = NamedTemporaryFile()
f.name = '/' + user + '/' + str(filename)
pdf = pisa.pisaDocument(BytesIO(template.encode('UTF-8')), f)
if not pdf.err:
return File(f)
return False
file = pdf_docs.convert_html_to_pdf(
template='https://www.example.com/sample.html',
context={'name': 'John Smith'},
filename='example.pdf',
)
In response, only the template URL is printed on PDF, not the content.
Javascript has a function called print. You can use the print method to convert the HTML to PDF. Here, is the code snippet to convert HTML to PDF. In addition, you can hide the text elements in JS before converting the HTML to pdf so that you will only get the template printed.
<html>
<head>
<title>Convert HTML to PDF</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnPrint").live("click", function () {
var divContents = $("#dvContainer").html();
var printWindow = window.open('', '', 'height=400,width=800');
printWindow.document.write('<html><head><title>DIV Contents</title>');
printWindow.document.write('</head><body >');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.print();
});
</script>
</head>
<body>
<form id="form1">
<div id="dvContainer">
This content needs to be printed.
</div>
<input type="button" value="Print Div Contents" id="btnPrint" />
</form>
</body>
</html>

Find Next in Google Apps

We have a bunch of documents we would like to convert to Google Docs. In MSWord we have a macro where our users hit a key command and it will automatically find a string of characters (%%%) and then select them. So we can quickly go in and replace all occurrences of them with the correct data.
I am unable to find anything in Google Docs or scripts that can do that.
TL;DR
I need to write a script that will find and select text so we can quickly write over it. Any help or thoughts?
This function works in conjunction with a sidebar to find and select text.
function findTextAndSelect(s){
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
var rgel=body.findText(s);
if(rgel){
var rgbldr=doc.newRange();
rgbldr.addElement(rgel.getElement(),rgel.getStartOffset(),rgel.getEndOffsetInclusive());
var rg=rgbldr.build();
if(rg.getRangeElements().length>0){
doc.setSelection(rgbldr.build());
return 'found';
}
else{
return 'Not Found';
}
}else{
return 'Not Found';
}
}
**This is the sidebar code. **
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
});
function findAndSelect(){
$('#status').html('');
var txt=$('#txt1').val();
google.script.run
.withSuccessHandler(function(hl){
$('#status').html('<strong>Status:</strong>' + hl);
})
.findTextAndSelect(txt);
}
console.log("My code");
</script>
</head>
<body>
<br />Text:<br /><textarea id="txt1" rows="6" cols="35"></textarea>
<br /><input type="button" id="btn3" value="Find Text and Select" onClick="findAndSelect();" />
<div id="status"></div>
</body>
</html>
You need to add the code to load the sidebar and possibly put it into the menu.

AJAX return from SmartyStreets API

I am having trouble actually returning any kind of object using this AJAX call. I know I am doing something wrong, but I have no idea where. I hope someone can help me I am looking to return an element in the object "zip". I would like to have any response really, but I can not get anything back.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var result = $('#resultDiv')
$.ajax({
url: 'https://us-street.api.smartystreets.com/street-address',
method: 'get',
data: {
auth-id='your-auth-id',
auth-token='your-auth-token',
street=$('#street'),
city=$('#city'),
state=$('#state')
},
dataType: 'json',
success: function(data) {
if (data = null)
{
result.html('You failed');
}
else {
result.html('Match:' + data.components[0].zipcode)
}
}
});
});
});
</script>
<title>SSTest</title>
</head>
<body>
<div class="container">
<h1 style="text-align:center"> Welcome to Address Check </h1>
<form action="#" method="post">
<div class="form-group">
<label for="street">Street</label>
<input type="text" id="street" class="form-control" name="street">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" class="form-control" name="city">
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" id="state" class="form-control" name="state">
</div>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
<br/>
<br/>
<div id="resultDiv"></div>
</body>
</html>
As you are using a GET call, you can test this in the browser first AND make sure you are getting a response before you start wrapping it in a JQuery call.
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=SOMETHING&state=SOMETHING&city=SOMETHING
If you get a non-result, then consult the API to see if you are passing the correct parameters.
Using the DOCS, this call returns data for your API Keys -
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10
This JQuery Get HTML example gets a response -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10", function(data, status){
alert("zipcode: " + JSON.stringify(data));
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
You should be able to build from that as you refine your JQuery understanding to get exactly what you need.
I was able to find a handful of errors with your code and fixed them here in this JSFiddle. Here are the list of errors you had.
Don't include your auth-id, auth-token in public code. You're giving away your address lookups by doing this. You should go remove these from your account and generate new ones.
In your original success function you didn't do a compare. You should use == here. Actually, the API will never send back null for data on success so you don't even need this here anymore. Use the error function instead.
The data object passed in the ajax call is done incorrectly. You should not be using =, instead use :.
In the data object you should call .val() after the jQuery selectors to get the values entered into those fields.
data.components[0].zipcode should be data[0].components.zipcode. The api will return back a data array of objects. components is not an array.
The auth-id and token should only be used when used from server side.
It is clearly mentioned not to expose the auth-id and auth-token in the documentation.
I used the FETCH API from Javascript and the code looks like this:
var key = '' //your embedded key here
var street = encodeURIComponent('1600 amphitheatre pkwy');
var city = encodeURIComponent('mountain view');
var state = 'CA';
var url = 'https://us-street.api.smartystreets.com/street-address?street=' + street + '&city=' + city + '&state=' + state + '&key=' + key;
const response = await fetch(url)
const responseData = await response.json()

Sending form data to spring controller using dojo

I've a list of records and want to update one. When I click on one, it show a form with all input fields which are already populated using JsonRest. I've edited the fields and now I want to send it to server for updating.
How can I send an Object with dojo?
I tried like this, but at the controller side the value is null.
on(dom.byId("poolForm"), "submit", function(evt) {
var formObj = domForm.toObject("poolForm");
console.log(formObj);
request.post("/path/to/EditSubmit", {
data : formObj,
method : "POST"
}). then(function(data) {
console.log("data");
});
});
In spring I used:
public void editedForm(HttpServletResponse response, #RequestBody MyClass myClass) {
poolParam.getAdd();
}
Assuming you are creating a new record and not updating one, you can use method add(object, options) for your JsonRest.
Example:
require(["dojo/store/JsonRest"], function(JsonRest){
// your store
var store = new JsonRest({
target: "/some/resource"
});
// add an object passing an id
store.add({
foo: "foo"
}, {
id: 1
});
});
More informations can be found at JsonRest API and JsonRest guide.
EDIT:
As for your comment request, in case you would like to send an object using dojo/request/xhr instead of JsonRest, you can use the following example, basically:
Use dojo/dom-form utility, to get out values from your form. This utility function will return an object. More info here.
Use dojo/request/xhr to send via Ajax the object previously retrieved from dojo/dom-form, this is the data sent to the server. More info here.
Quick demo here:
https://jsbin.com/mocoxuhotu/edit?html,output
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css">
<script data-dojo-config="async: 1" src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script>
require([
"dojo/query",
"dojo/dom-form",
"dojo/request/xhr",
"dijit/registry",
"dijit/form/Form",
"dojo/parser",
"dojo/domReady!"
], function (
query,
domForm,
xhr,
registry,
Form,
parser
) {
var form = new Form({}, 'myForm');
query("a.myLink").on("click", function () {
var data = domForm.toObject(form.domNode);
xhr.post("/echo/json", {
data: data // data to transfer
}).then(function () {
console.log("Success");
});
});
});
</script>
</head>
<body class="claro">
<form data-dojo-type="dijit/form/Form" id="myForm">
<fieldset>
<ul>
<li>
<label for="name">Name:</label>
<input type="text" name="name" />
</li>
<li>
<label for="firstname">First name:</label>
<input type="text" name="firstname" />
</li>
</ul>
</fieldset>
</form>
<a class="myLink">Submit the form</a>
</body>
</html>