R github rendering js files to see googleVis html - javascript

Using R, I would like to be able to render an .html or .md file (that has either been created via knitr or some other manner) that contains googleVis charts in a repo in github.
I was trying to follow the help file when running ?plot.gvis, and I have tried pushing up the gvisData.js and gvisFunctions.js files into the repo and altered the html to reference these, but I have a feeling that I dont quite have the correct baseURL in order for github to be able to render it correctly.
Does anybody have a simple example of a URL that references Github that renders googleVis charts?
I have tried using this http://lamages.blogspot.co.uk/2013/07/googlevis-tutorial-at-user2013.html but didn't see how it would work with github...
So using the example given in ?plot.gvis this is what I tried
myChartID <- "mtnc"
baseURL <- "https://raw.github.com/USER/REPO"
wwwdir <- getwd() ## the working directory is the local directory of the repo
## Create a motion chart
M <- gvisMotionChart(Fruits, "Fruit", "Year", chartid=myChartID)
## Write the data and functions into separate files:
cat(M$html$chart['jsData'], file=file.path(wwwdir, "gvisData.js"))
cat(M$html$chart[c('jsDrawChart', 'jsDisplayChart', 'jsChart')],
file=file.path(wwwdir, "gvisFunctions.js"))
## Create a html page with reference to the above
## JavaScript files
html <- sprintf('
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript" src="%s/gvisFunctions.js"></script>
<script type="text/javascript" src="%s/gvisData.js"></script>
<script type="text/javascript">
displayChart%s()
</script>
</head>
<body>
<div id="%s" style="width: 600px; height: 500px;"></div>
</body>
</html>
', baseURL, baseURL, myChartID, myChartID)
## Write html scaffold into a file
cat(html, file=file.path(wwwdir, paste("Chart", myChartID, ".html", sep="")))
### from this point I push up to the repo the following files
### gvisData.js, gvsiFunctions.js and Chartmtnc.html
## Display the result via
URL <- paste(baseURL,"/Chart", myChartID, ".html", sep="")
browseURL(URL)
Any suggestions would be useful...

You are complicating it unnecessarily. You just need to do one thing, when you are trying to use a googleVis chart in a knitr document, which is to set
options(gvis.plot.tag = 'chart')
You can see a published example here and the source file can be found here

Related

How to add script to head tag in MkDocs?

I am new to MkDocs and I built up a website using MkDocs and I want to add some script into <head>...</head>.
I tried this code at top of my markdown file but it didn't work :
<head>
<script>
...
</script>
</head>
I found the script would show in <body>...</body> rather than in <head>...</head>.
How to place <script> in <head> tag?
You can use material. in your theme (mkdocs.yml), add a reference to custom dir, and in that dir, you can add a file named main.html which will be included in the "head" part
See https://squidfunk.github.io/mkdocs-material/customization/#overriding-partials for more details.
Assuming your are using MkDocs Material as your Theme, inside your mkdocs.yml you can add Entries to the extra_javascript List.
mkdocs.yml:
site_name: "..."
theme: "..."
# ...
extra_javascript:
- https://cdn.someCdn.someLibrary.js # Online Resource
- js/ourJsFile.js # Path relative to "docs" Directory
# Works the same way for CSS!
extra_css:
- css/someCSS.css # Again, relative to the "docs" Directory
For reference: https://squidfunk.github.io/mkdocs-material/customization/#adding-assets
The extrahead placeholder, which should be present in all themes, allows additions to be made to the <head>.
You need to specify a custom_dir in the YAML file and in this directory have a main.html with an extrahead block.
See:
https://www.mkdocs.org/user-guide/customizing-your-theme/#using-the-theme_dir
Try this:
<!DOCTYPE html>
<html>
<head>
<script src="https://file.js"></script>
</head>
<body>
{{ content }}
</body>
</html>

Serving an Iframe in Google Colab Notebook: localhost refused to connect

I am trying to serve some HTML from a Google Colab notebook using the following:
from IPython.display import IFrame
IFrame(src='./output/index.html', width=700, height=600)
However, this throws localhost refused to connect:
Does anyone know how I can serve the html in index.html (which must load javascript) inside the Colab notebook? Any pointers would be hugely appreciated!
You can serve content from the path /nbextensions/ which maps to /usr/local/share/jupyter/nbextensions.
So you can put content there.
!ln -s /usr/local/share/jupyter/nbextensions /nbextensions
%cd /nbextensions
!wget -q https://upload.wikimedia.org/wikipedia/commons/3/37/Youtube.svg
Then serve the image
%%html
<img src=/nbextensions/Youtube.svg>
I can't make it works with IFrame, thought. I don't know why.
Here's an example colab notebook.
This built-in example notebook gives a demo:
https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=R8ZvCXC5A0wT
Reproducing the example here of serving content from the backend:
import portpicker
import threading
import socket
import IPython
from six.moves import socketserver
from six.moves import SimpleHTTPServer
class V6Server(socketserver.TCPServer):
address_family = socket.AF_INET6
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
# If the response should not be cached in the notebook for
# offline access:
# self.send_header('x-colab-notebook-cache-control', 'no-cache')
self.end_headers()
self.wfile.write(b'''
document.querySelector('#output-area').appendChild(document.createTextNode('Script result!'));
''')
port = portpicker.pick_unused_port()
def server_entry():
httpd = V6Server(('::', port), Handler)
# Handle a single request then exit the thread.
httpd.serve_forever()
thread = threading.Thread(target=server_entry)
thread.start()
# Display some HTML referencing the resource.
display(IPython.display.HTML('<script src="https://localhost:{port}/"></script>'.format(port=port)))
This works for me on Aug 2022:
First, as #korakot mentioned, if you have any javascript used in your html, please copy them into /usr/local/share/jupyter/nbextensions
e.g.
!cp -r ./output/ /usr/local/share/jupyter/nbextensions/google.colab/
use !ls /usr/local/share/jupyter/nbextensions/google.colab/ to check if file already exists
Then, instead of referring to html file by path, simple copy the html code in <body> into colab cell:
%%html
<!-- move your head part resources here -->
<script src="/nbextensions/google.colab/output/xxxx.js"></script>
<link type="text/css" href="/nbextensions/google.colab/outut/xxxx.css" rel="stylesheet" />
<!-- here is your body code -->
<div id="files"></div>
<div id="canvasArea" height="720px"></div>
...
<script>
// set the cell height
google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
// you can also log some testing code here, to check whether it works or not
console.log("hello world");
console.log(variables_in_your_js)
</script>
Run the cell to check whether works or not.

Import external JS scripts in Google Colab html

I am having a hard time importing my custom external JS files to Google Colab. I work with html + js, following this workflow:
1 / imports
from IPython.display import HTML, SVG
from IPython.core.magic import register_cell_magic
2 / mount drive
from google.colab import drive
drive.mount('/content/drive')
3 / html
#register_cell_magic
def dojs(line, src):
return HTML(f"""
<canvas id="renderCanvas" touch-action="none" width="1280px" height="720px"></canvas>
<script src="content/drive/My Drive/Colab Notebooks/files/testJavascript.js"></script>
<script>
{src}
</script>
""")
4 / js
%%dojs
//...trying to use functions from testJavascript.js
Maybe it's really trivial how to do this but I'm new at Colab. I get "Failed to load resource: the server responded with a status of 500 ()".
You need to put your JS file in here:
/usr/local/share/jupyter/nbextensions/google.colab/
Then it can be access through the path
/nbextensions/google.colab/
In your case, you need to copy your js file there:
!cp /content/drive/My\ Drive/Colab\ Notebooks/files/testJavascript.js \
/usr/local/share/jupyter/nbextensions/google.colab/
Then change dojs() to be
#register_cell_magic
def dojs(line, src):
return HTML(f"""
<canvas id="renderCanvas" touch-action="none" width="1280px" height="720px"></canvas>
<script src="/nbextensions/google.colab/testJavascript.js"></script>
<script>
{src}
</script>
""")
Lines like script src="content/drive... won't work. The reason is that your Drive files are present on the backend VM executing your code. But, using a <script> tag is going to be resolved by your browser against the current base origin, which is colab.research.google.com, which doesn't serve your Drive files.
There are some recipes for serving local files in the advanced outputs example here:
https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=R8ZvCXC5A0wT

Umbraco property editor not working

I'm running Umbraco version 7.9.2 and following this tutorial to learn how to create custom property editors.
My first step was to create a folder called MarkDownEditor
My second step was to create a file named package.manifest.json
{
//you can define multiple editors
"propertyEditors": [
{
/*this must be a unique alias*/
"alias": "My.MarkdownEditor",
/*the name*/
"name": "My markdown editor",
/*the icon*/
"icon": "icon-code",
/*grouping for "Select editor" dialog*/
"group": "Rich Content",
/*the HTML file we will load for the editor*/
"editor": {
"view": "~/App_Plugins/MarkDownEditor/markdowneditor.html"
}
}
],
//array of files we want to inject into the application on app_start
"javascript": [
"~/App_Plugins/MarkDownEditor/markdowneditor.controller.js"
]
}
I then created two files: markdowneditor.controller.js and markdowneditor.html in the MarkDownEditor directory
markdowneditor.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div ng-controller="My.MarkdownEditorController">
<textarea ng-model="model.value"></textarea>
</div>
</body>
</html>
markdowneditor.controller.js
angular.module("umbraco")
.controller("My.MarkdownEditorController",
//inject umbracos assetsService
function ($scope, assetsService) {
//tell the assetsService to load the markdown.editor libs from the markdown editors
//plugin folder
assetsService
.load([
"~/App_Plugins/MarkDownEditor/lib/Markdown.Converter.js",
"~/App_Plugins/MarkDownEditor/lib/Markdown.Sanitizer.js",
"~/App_Plugins/MarkDownEditor/lib/Markdown.Editor.js"
])
.then(function () {
//this function will execute when all dependencies have loaded
alert("editor dependencies loaded");
console.log('stuff has loaded!');
});
//load the separate css for the editor to avoid it blocking our js loading
assetsService.loadCss("~/App_Plugins/MarkDownEditor/lib/Markdown.Editor.css");
});
Finally, I registered the editor in the Umbraco CMS, put it in a simple document type and finally visited the page in multiple browsers.
And... I see nothing. It seems like the editor is working (I think) but I don't get why I'm not seeing my alert or console.log that's contained in the controller. What did I do wrong? I've tried multiple browsers so I know it's not a caching issue and I've made sure to rebuild the project in visual studio.
Edit 1 :
Per suggestions, I've tried modifying the assetService file paths since ~ seems to be a C# thing and my controller is a javascript file. It now looks like this
.load([
"/App_Plugins/MarkDownEditor/lib/Markdown.Converter.js",
"/App_Plugins/MarkDownEditor/lib/Markdown.Sanitizer.js",
"/App_Plugins/MarkDownEditor/lib/Markdown.Editor.js"
])
However, I'm still not seeing an alert or a console log.
One thing I did realize I was doing wrong was not including my markdown value in the markdown template. I've done that and now see the content that I put in the editor when creating a new markdown page.
Simple solution. My package.manifest file had a .json extension. When that was removed, everything worked perfectly. For anyone coming across this, the ~ works perfectly fine in the javascript file.

Cloudinary + Sails.js direct upload doesn't work

i'm trying to make cloudinary direct upload working but something in the documentation is missing... here are the steps i'm doing:
Controller:
/**
* MyaccountController
*
* #description :: Server-side logic for managing myaccounts
* #help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'MyCloudName',
api_key: 'MyAPIKey',
api_secret: 'MyAPISecret'
});
Now this is my layout:
<!--SCRIPTS-->
<script type="text/javascript" src="/js/dependencies/sails.io.js"></script>
<script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
<script type="text/javascript">
cloudinary.cloudinary_js_config();
var cloudinary_cors = "http://" + window.location.host + "/cloudinary_cors.html";
console.log(cloudinary_cors);
cloudinary.uploader.image_upload_tag('photo', { callback: cloudinary_cors });
$(".photo").cloudinary_fileupload();
// Using the config function
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
</script>
My form:
<form action="" method="post" enctype="multipart/form-data" class="upload_form">
<div class="form-group">
<label>Foto de perfil</label>
<input type="file" name="photo" id="photo" class="photo">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Cargar</button>
</div>
</form>
I don't get why it isn't working, in the docs it says Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters to be available. Note: never expose your api_secret in public client side code.
To automatically set-up Cloudinary's configuration, include the following line in your view or layout:
cloudinary.cloudinary_js_config()
This is done...
Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.
This solution requires placing cloudinary_cors.html in the static folder of your Node application. This file is available in the html folder of Cloudinary's Javascript library. The following code builds a URL of the local cloudinary_cors.html file:
Done...
Direct upload file tag
Embed a file input tag in your HTML pages using the image_upload_tag view helper method.
The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.
cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors });
this is what i don't get... this is the uploader? how should i use it? and then i don't know what else to do, i'm using different docs to make it work but nothing helps... I hope anyone who did this can help me, thanks!
On controller initialize cloudinary as
var uploader = cloudinary.uploader.image_upload_tag('image_id', { callback: cloudinary_cors, html: { multiple: 1 } });
and pass it to view and render it over there,
<%-uploader%>
then use jquery to get data:
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {}
you can use this script to bind the data to some hidden fields inside your form and
cloudinary-fileupload will be generated when <%-uploader%> is rendered
In addition to CodeBean's answer, note that it seems that there are different ways of using Cloudinary that are mixed here (in the original code as was in question).
Controller
As far as it can be seen from here, the MyaccountController controller doesn't do a thing:
You're requiring "cloudinary" - presumably from npm install, which creates an instance of the jQueryless Cloudinary class.
The variable is local to the controller so has no effect on the rest of the code
View:
Only one of these lines is required (preferably the second one):
<script type="text/javascript" src="/js/jquery.cloudinary.js"></script>
<script src="../node_modules/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
This method returns a string with the <script> tag. The string should be then embedded in the HTML code. It is a server side code.
Here, it does nothing.
cloudinary.cloudinary_js_config();
If you're using the jQuery File Upload code, you should refer to $.cloudinary. cloudinary was never defined in your layout.
Now you're creating a jQueryless instance, which you don't use afterwards.
var cl = cloudinary.Cloudinary.new();
cl.config( "MyCloudName", "MyAPIKey");
Finally, there's an open-ended comment with the code you were supposed to use in the beginning of the whole script:
/*
$.cloudinary.config({ cloud_name: 'MyCloudName', api_key: 'MyAPIKey'});
Regardless of CodeBean's response, you still need to config $.cloudinary.

Categories

Resources