Provide file download links in iJulia notebook results - julia

I'd like to produce a data file that is downloaded by the user, either automatically or through a hyperlink.
For instance, is there an equivalent of this iPython approach for iJulia?

If I understand your question correctly, you're looking to auto-generate a link in Jupyter Notebook, such that people can download? If so, I do this in Vega.jl (so people can download PNG files of graphs) with the following:
window.setTimeout(function() {
var pnglink = document.getElementById(\"$divid\").getElementsByTagName(\"canvas\")[0].toDataURL(\"image/png\")
document.getElementById(\"$divid\").insertAdjacentHTML('beforeend', '<br><a href=\"' + pnglink + '\" download>Save as PNG</a>')
}, 20);
https://github.com/johnmyleswhite/Vega.jl/blob/master/src/render.jl#L65-L69
Basically, this code finds the div that the output is in (which is known at the time of Julia code running, before the output is rendered), then auto-generates an HTML link with the base64 representation of the PNG. Depending on your content, this obviously may differ (since the .toDataURL method has to have your file type in the method).

I translated from original FileLink definition to julia:
type FileLink
file_path::ByteString
end
type FileLinks
links::Vector{FileLink}
end
FileLinks(paths::Vector{ByteString}) = FileLinks(map(FileLink,paths))
function Base.writemime(st::IO, ty::MIME"text/html", fl::FileLink)
write(st, "<a href=$(fl.file_path) target='_blank'>$(fl.file_path)</a>")
end
function Base.writemime(st::IO, ty::MIME"text/html", file_links::FileLinks)
for fl in file_links.links
Base.writemime(st, ty, fl)
write(st,"<br>")
end
end
FileLinks(readdir("."))
Works on locally hosted IJulia/IPython/Jupyter server, but you may have problems with remote servers (eg Sage).

Using NBViewer to serve Jupyter notebooks statically works also with IJulia.
http://nbviewer.jupyter.org/gist/Ismael-VC/3d54a43d73f3a3fbd922
As shown in it's home page:
In this example I give NBViewer the link of one of my IJulia notebooks that is hosted in Gist, notice that GitHub/Gist now also renders Jupyter noteboks:
https://gist.github.com/Ismael-VC/3d54a43d73f3a3fbd922

Related

Why do some functions open in the read-only mode in RStudio?

I am debugging my scripts in RStudio and came across a strange behaviour. For all my working functions, when I Command + click (ctrl + click), I get to the script of that functions.
However, for my one function when I do that it opens only read only mode. Does that mean the function is buggy? How can I fix this behaviour?
It depends on how the function was loaded: when you source the whole file, RStudio associates the function with its source file, and can jump to its definition. If, by contrast, you’ve loaded the function by e.g. only executing a single code fragment, RStudio doesn’t know which source file the function is associated with.
If you then subsequently want to jump to its definition, RStudio creates a temporary file which contains a deparsed representation of the function, not the original source. And since that file isn’t the original source but rather a temporary, RStudio marks it as read-only.

How to insert image on Jupyter Notebook

I am using macOS and trying to add an image (png) file on Jupyter Notebook markdown cell, but it keeps generating an error message that they cannot find the png file. I am not sure what is wrong with my following two codes:
![alt text]("~Users/jj/pythonworkspace/what.is.numpy.png" "What is Numpy?")
Alternatively,
<img src="~Users/jj/pythonworkspace/what.is.numpy.png">
You shouldn't be using quotations around your path or links. Also i think you meant to have an additional / after your home directory or maybe not have ~ at all. The path you're providing isn't following the macOS conventions.
You can test if that path is valid by going into terminal and running
ls /path/you/are/testing
try
![What is Numpy?](/Users/jj/pythonworkspace/what.is.numpy.png)

Shortcut control enter does not work in R script

ctrl+R no longer works for executing script lines.
This is not a hardware/keyboard problem.
I have also restarted my PC.
I have tried on a different PC.
I have recently switched from using R to using RStudio. I thought this may have something to do with it, so I opened and resaved the script in RStudio, to no effect.
Furthermore, I have created an R-Project folder and have copied the files, including the script in question, into it. Then I started R-Studio and opened the project.
I would like to post my sessionInfo(), but do not know how to do that without executing the command.
Keep in mind that I only use R for stats purposes. I don't know much about informatics or other types of programming etc., so please try to keep it simple for me. Thanks!
In addition to the solution offered above, in Rstudio, Ctrl + Enter does not work if the chunk is broken in .Rmd files.
For example, if you press CTRL + Enter on the following line (2+2), it won't work:
```{r}
2+2
``
The chunk should end three Backtick characters, not two.
The problem was that the script file (for some reason unkown to me) did not have the correct extension (.R). When I added that to the script file extension, it worked fine again.

Need ui.R to get path for input file/directory as string

I have a fair-size R program that processes all text files (running LSA) in a given directory. It works, but it's not exactly user-friendly, and I'm trying to use Shiny to fix that. The problem is simply giving users a nice way to choose a directory and getting the path to it; then I can pass the path to my R program. Something like this:
fileInput("corpDir", label = "Choose the directory containing the corpus.")
...then, in Server.R, get the path via input$corpDir and pass it to the R program. But the fileInput widget does both too much (I don't want to upload the file, I just want to get its path) and too little (it returns the filename but not the path). And R's file.choose would be fine -- well, it'd be better if it allowed choosing directories, but having users choose a file within the directory is OK -- but I don't see how I can use file.choose from a Shiny UI. I've looked around on the RStudio site, including their gallery of examples, and tried to find an answer in both the Google group and here. I didn't find anything like this. TIA for any suggestions.
The shinyFiles package can do that!
just install the package and run shinyFilesExample() to see how it works.
(NB: it only works if your shiny app runs locally, you can look at https://github.com/jcolomb/Viewer-file-concatenator and its readme for an example)

get filename and path of `source`d file

How can a sourced or Sweaved file find out its own path?
Background:
I work a lot with .R scripts or .Rnw files.
My projects are organized in a directory structure, but the path of the project's base directory frequently varies between different computers (e.g. because I just do parts of data analysis for someone else, and their directory structure is different from mine: I have projects base directories ~/Projects/StudentName/ or ~/Projects/Studentname/Projectname and most students who have just their one Project usually have it under ~/Measurements/ or ~/DataAnalysis/ or something the like - which wouldn't work for me).
So a line like
setwd (my.own.path ())
would be incredibly useful as it would allow to ensure the working directory is the base path of the project regardless of where that project actually is. Without the need that the user must think of setting the working directory.
Let me clarify: I look for a solution that works with pressing the editor's/IDE's source or Sweave Keyboard shortcut of the unthinking user.
Just FYI, knitr will setwd() to the dir of the input file when (and only when) evaluating the code chunks, i.e. if you call knit('path/to/input.Rnw'), the working dir will be temporarily switched to path/to/. If you want to know the input dir in code chunks, currently you can call an unexported function knitr:::input_dir() (I may export it in the future).
Starting from gsk3's Seb's suggestions, here's an idea:
the combination of username (login) and IP or name of the computer could be used to select the right directory.
That leads to something like:
setwd (switch (paste (Sys.info () [c ("user", "nodename")], collapse="."),
user.laptop = "~/Messungen",
user2.server = "~/Projekte/Projekt/",
))
So there is an automatic solution, that
works with source
works with Sweave
even works for interactive sessions where the commands are sent line by line
the combination of user and nodename of course needs to be specific
the paths need to be edited by hand, though.
Improvements welcome!
Update:
Gabor Grothendieck answered the following to a related question on r-help today:
this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)
which will work for source.
Another update: I now do most of the data analysis work in RStudio. RStudio's projects basically solve the problem: RStudio changes the working directory to the project root directory every time I switch between projects.
I can therefore put the project directory as far down my directory tree as I want (and the students can also put their copy wherever they want) and sync the data files and scripts/.Rnws via version control (We use a private git server). The RStudio project files are kept out of the version control, i.e. .gitignore contains .Rproj.user.
Obviously, within the project, the directory structure needs to be synchronized.
You can use sys.calls() to get the command used to source the file. Then you need a bit of trickery using regular expressions to get the pathname, bearing in mind that source("something/filename") could have used either the absolute or relative path. Here's a first attempt at putting all the pieces together: try inserting the following lines at the top of a source file.
whereFrom=sys.calls()[[1]]
# This should be an expression that looks something like
# source("pathname/myfilename.R")
whereFrom=as.character(whereFrom[2]) # get the pathname/filename
whereFrom=paste(getwd(),whereFrom,sep="/") # prefix it with the current working directory
pathnameIndex=gregexpr(".*/",whereFrom) # we want the string up to the final '/'
pathnameLength=attr(pathnameIndex[[1]],"match.length")
whereFrom=substr(whereFrom,1,pathnameLength-1)
print(whereFrom) # or "setwd(whereFrom)" to set the working directory
It's not very robust—for instance, it will fail on windows with source("pathname\\filename"), and I haven't tested what happens if you have one file sourcing another file—but you might be able to build a solution on top of this.
I have no direct solution how to obtain the directory of the file itself but if you have a limited range of directories and directory structures you can probably use
if(file.exists("c:/somedir")==TRUE){setwd("c:/somedir")}
You could check out the pattern of the directory in question and then set the dir. Does this help you?
An additional problem is that the working directory is a global variable, which can be changed by any script, so if your script calls another script, it will have to set the wd back. In RStudio I use Session -> Set Working Directory -> To Source File Location (I know, it's not ideal), and then my script does
wd = getwd ()
...
source ("mySubDir/myOtherScript.R", chdir=TRUE); setwd (wd)
...
source ("anotherSubDir/anotherScript.R", chdir=TRUE); setwd (wd)
In this way one can maintain a stack of working directories. I would love to see this implemented in the language itself.
This answer works for source and also inside nvim-R - I have no idea if it works with knitr and similar things. Any feedback appreciated.
If you have multiple scripts source-ing each other, it is important to get the correct one. That is, the largest i for which sys.frame(i)$ofile exists.
get.full.path.to.this.sourced.script = function() {
for(i in sys.nframe():1) { # Go through all the call frames,
# in *reverse* order.
x = sys.frame(i)$ofile
if(!is.null(x)) # if $ofile exists,
return(normalizePath(x)) # then return the full absolute path
}
}

Resources