I'm trying to create a shiny R application. I have some troubles to show euro symbol (and return it) in a radio button. I've tried different version of code:
library(shiny)
runApp(list(
ui= navbarPage(title = 'shoe euro',
radioButtons('var', 'var',
c("INCOME_MGL",
"INCOME_MGL€",
"INCOME_MGL€",
"INCOME_MGL€",
"INCOME_MGL\u20ac")
)),
server=function(input, output, session) {
}))
But the "€" doesn't appear in the web page. Moreover if I select the second option the page returns an error:
"Error in fromJSON(content, handler, default.size, depth, allowComments, :
invalid JSON input"
The problem lies in the class shiny-options-group in the div function. The way this class works appears to convert & to &, preventing the browser from converting € into € because it first changes it into €. Try the following as your ui.R to see it happen.
library(shiny)
options = as.list(c("a","b",HTML("€"),"€"))
shinyUI(fluidPage("test",fluidRow(div(class = "shiny-options-group", options))))
The reason this is happening in your radio button widget is that radioButtons calls generateOptions to create the list of options, and generateOptions returns div(class = "shiny-options-group", options), where options is derived from a manipulation of the choices parameter in the radioButtons function. Here is what you could do:
Get the code for generateOptions here (line 653).
Define the new function generateOptions2 using the exact same code as generateOptions, but change the class parameter at the end.
Get the code for radioButtons by running shiny::radioButtons
Define a new function radioButtons2 and in it replace the generateOptions with generateOptions2.
Set the environment for both new functions to shiny by running something like environment(radioButtons2) <- environment(radioButtons)
Use radioButtons2 in your code instead of radioButtons
The only thing I don't know is what to change the class parameter to in generateOptions2. I don't know much about div classes.
Update
I may have spoken too soon. It looks like the problem goes far deeper. The div function calls tags$div, which calls tag with the first argument set to "div". tag then calls the base function structure with the parameter class = "shiny.tag". structure then calls the primitive function attributes with the parameter class = "shiny.tag". attributes with this parameter then converts & in to &. Therefore, it looks like there is no way to use the div function and get back the euro symbol. I tried replacing div in generateOptions2 with HTML, but that returned a bunch of garbage when I ran the app. You'd have to change the behavior of class = "shiny.tag", but that could have far-reaching unpredictable effects.
Update 2
Figured it out! The trick is to use gsub to replace every & with just & before it is returned from generateOptions2. I put a functioning version of what you posted on github. It requires loading the two functions I mentioned earlier, which (in my repository) are stored in a file called functions.R. The important line in generateOptions2 is gsub(pattern = "&", replacement = "&", div(class = "shiny-options-group", options)).
Related
I'm switching over to using the Auto-IVC component as opposed to the IndepVar component. I'd like to be able to get a list of the promoted output names of the Auto-IVC component, so I can then use them to go and pull the appropriate value out of a configuration file and set the values that way. This will get rid of some boilerplate.
p.model._auto_ivc.list_outputs()
returns an empty list. It seems that p.model__dict__ has this information encoded in it, but I don't know exactly what is going on there so I am wondering if there is an easier way to do it.
To avoid confusion from future readers, I assume you meant that you wanted the promoted input names for the variables connected to the auto_ivc outputs.
We don't have a built-in function to do this, but you could do it with a bit of code like this:
seen = set()
for n in p.model._inputs:
src = p.model.get_source(n)
if src.startswith('_auto_ivc.') and src not in seen:
print(src, p.model._var_allprocs_abs2prom['input'][n])
seen.add(src)
assuming 'p' is the name of your Problem instance.
The code above just prints each auto_ivc output name followed by the promoted input it's connected to.
Here's an example of the output when run on one of our simple test cases:
_auto_ivc.v0 par.x
I am searching for a way to get user input inside a loop while executing in batch mode.
readLines() and scan() work well for me in interactive mode only, in batch mode they start to read in lines of code as user input, unless all the code is surrounded by {}, which is inconvenient. I need a simple solution to get just 1 integer value in a way that I can just type in value and press ENTER, so
the input field (if the solution involves GUI) must automatically get focus and
ENTER must trigger end of input/submission.
I can't find a way to do it that will satisfy both conditions, e.g. ginput() from gWidgets activates the input field, but ENTER doesn't trigger form submission.
Here is how I solved my own problem:
require(gWidgets)
options(guiToolkit="RGtk2")
INPUT <- function(message) {
CHOICE <- NA
w <- gbasicdialog(title=message, handler = function(h,...) CHOICE <<- svalue(input))
input <- gedit("", initial.msg="", cont=w, width=10)
addHandlerChanged(input, handler=function (h, ...) {
CHOICE <<- svalue(input)
dispose(w)
})
visible(w, set=TRUE)
return(CHOICE)
}
repeat{
x=INPUT("Input an integer")
if(!is.na(as.integer(x))) break
}
print(x)
Update:
I can't test this right now, but take a look at ?menu and have it pop up a gui window.
I'm not certain if that will work, but it is different in that it takes a mouse-click response.
original answer:
As per the documentation to ?readline:
This can only be used in an interactive session.
..
In non-interactive use the result is as if the response was RETURN and the value is "".
If you are simply waiting for one piece of information, and you do not know this piece of information before beginning the execution of the script (presumably, there is a decision to be made which is dependent on the results earlier in the script), then one alternative is to simply break your script up into three parts:
everything before the decision point.
an interactive script which prompts for input
everything after the decision point.
And simply chain the three together by having the first end by calling the second in an interactive session. Then have the second end by calling the third.
I am running WYSIHTML5 to allow myself to enter email text and format it for sending as HTML. However when I view HTML of the formatted text I get classes associated with elements for Colors. This is expected behavior but since I need to send the output in an email hence I would like to have those colors to be in Inline CSS, since I cannot attach CSS files with the email like that. Example here
<span class="wysiwyg-color-green">Testing</span>
That is if I select green color for text: Testing. Is there any way to modify that green to become part of html itself like
<span style="color:green">Testing</span>
I have tried to search for this but could not find, so I am not asking without first looking for it. If anybody could please just point somewhere. Even a link to any guide to this, will do. I do not wish that you spend time writing code for me.
You could do it with php :
str_replace ( 'class="wysiwyg-color-green"', 'style="color:green"' ,$html)
You can do the same with javascript, altrough it's always safer to do everything server-side.
http://www.w3schools.com/jsref/jsref_replace.asp
Here's the javascript code I used but may be a good idea to heed Jean-Georges warning above:
replaceColorStylesWithInlineCss = function (htmlContents){
result = htmlContents.replace('class="wysiwyg-color-black"', 'class="wysiwyg-color-black" style="color:black"');
result = result.replace('class="wysiwyg-color-silver"', 'class="wysiwyg-color-silver" style="color:silver"');
result = result.replace('class="wysiwyg-color-gray"', 'class="wysiwyg-color-gray" style="color:gray"');
result = result.replace('class="wysiwyg-color-maroon"', 'class="wysiwyg-color-maroon" style="color:maroon"');
result = result.replace('class="wysiwyg-color-red"', 'class="wysiwyg-color-red" style="color:red"');
result = result.replace('class="wysiwyg-color-purple"', 'class="wysiwyg-color-purple" style="color:purple"');
result = result.replace('class="wysiwyg-color-green"', 'class="wysiwyg-color-green" style="color:green"');
result = result.replace('class="wysiwyg-color-olive"', 'class="wysiwyg-color-olive" style="color:olive"');
result = result.replace('class="wysiwyg-color-navy"', 'class="wysiwyg-color-navy" style="color:navy"');
result = result.replace('class="wysiwyg-color-blue"', 'class="wysiwyg-color-blue" style="color:blue"');
result = result.replace('class="wysiwyg-color-orange"', 'class="wysiwyg-color-orange" style="color:orange"');
return result
};
Note: I kept the wysiwyg styles in there because I'm saving to the db and want it to display properly in the wysihtml5 section when I load it again. DRY it up if you're clever.
I am trying to use ControlCommands with a .NET application (hence, these should all be standard Microsoft controls), but most of the ones that are of interest don't seem to do anything.
I am currently looking at a combobox (the drop down box). I used the "showdropdown" command to have it drop down, and it worked successfully.
I then tried to use "SelectString", but it didn't go to the string that I specified. How does the "SelectString" ControlCommand option work?
I have also tried "SetCurrentSelection".
This is the statement I used:
ControlCommand($windowName, "", "[Name:myComboBox]", "SelectString", "a")
I have also tried searching for it first with:
ControlCommand($windowName, "", "[Name:myComboBox]", "FindString", "a")
but it didn't find it either. Strange, the single character "a" is there.
If it helps, this is the control class: WindowsForms10.COMBOBOX
_GUICtrlComboBox_xxx functions also work on external controls. For example, _GUICtrlComboBox_FindString, _GUICtrlComboBox_SelectString, _GUICtrlComboBox_SetCurSel. Try those instead.
Call ControlGetHandle first, then use this handle to call the functions above.
Remember to include the GuiComboBox library, otherwise you will get an error message "Error: Unknown function name":
#include <GuiComboBox.au3>
You can send key presses to this control, like this:
ControlSend("Window title", "", "[NAME:comboBoxName]", "ComboBox value")
It works because ComboBox interprets input as a search string and selects the first item starting with this string.
Note: Because it searches the matching item as you type, there's no need to send a complete value, only the shortest substring.
I (sort of) already know the answer to this question. But I figured it is one that gets asked so frequently on the R Users list, that there should be one solid good answer. To the best of my knowledge there is no multiline comment functionality in R. So, does anyone have any good workarounds?
While quite a bit of work in R usually involves interactive sessions (which casts doubt on the need for multiline comments), there are times when I've had to send scripts to colleagues and classmates, much of which involves nontrivial blocks of code. And for people coming from other languages it is a fairly natural question.
In the past I've used quotes. Since strings support linebreaks, running an R script with
"
Here's my multiline comment.
"
a <- 10
rocknroll.lm <- lm(blah blah blah)
...
works fine. Does anyone have a better solution?
You can do this easily in RStudio:
select the code and click CTR+SHIFT+C
to comment/uncomment code.
This does come up on the mailing list fairly regularly, see for example this recent thread on r-help. The consensus answer usually is the one shown above: that given that the language has no direct support, you have to either
work with an editor that has region-to-comment commands, and most advanced R editors do
use the if (FALSE) constructs suggested earlier but note that it still requires complete parsing and must hence be syntactically correct
A neat trick for RStudio I've just discovered is to use #' as this creates an self-expanding comment section (when you return to new line from such a line or insert new lines into such a section it is automatically comment).
[Update] Based on comments.
# An empty function for Comments
Comment <- function(`#Comments`) {invisible()}
#### Comments ####
Comment( `
# Put anything in here except back-ticks.
api_idea <- function() {
return TRUE
}
# Just to show api_idea isn't really there...
print( api_idea )
`)
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate!")
}
foo()
[Original Answer]
Here's another way... check out the pic at the bottom. Cut and paste the code block into RStudio.
Multiline comments that make using an IDE more effective are a "Good Thing", most IDEs or simple editors don't have highlighting of text within simple commented -out blocks; though some authors have taken the time to ensure parsing within here-strings. With R we don't have multi-line comments or here-strings either, but using invisible expressions in RStudio gives all that goodness.
As long as there aren't any backticks in the section desired to be used for a multiline comments, here-strings, or non-executed comment blocks then this might be something worth-while.
#### Intro Notes & Comments ####
invisible( expression( `
{ <= put the brace here to reset the auto indenting...
Base <- function()
{ <^~~~~~~~~~~~~~~~ Use the function as a header and nesting marker for the comments
that show up in the jump-menu.
--->8---
}
External <- function()
{
If we used a function similar to:
api_idea <- function() {
some_api_example <- function( nested ) {
stopifnot( some required check here )
}
print("Cut and paste this into RStudio to see the code-chunk quick-jump structure.")
return converted object
}
#### Code. ####
^~~~~~~~~~~~~~~~~~~~~~~~~~ <= Notice that this comment section isnt in the jump menu!
Putting an apostrophe in isn't causes RStudio to parse as text
and needs to be matched prior to nested structure working again.
api_idea2 <- function() {
} # That isn't in the jump-menu, but the one below is...
api_idea3 <- function() {
}
}
# Just to show api_idea isn't really there...
print( api_idea )
}`) )
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate and cause an error!")
}
foo()
## [1] "The above did not evaluate and cause an error!"
And here's the pic...
I can think of two options. The first option is to use an editor that allows to block comment and uncomment (eg. Eclipse). The second option is to use an if statement. But that will only allow you to 'comment' correct R syntax. Hence a good editor is the prefered workaround.
if(FALSE){
#everything in this case is not executed
}
If find it incredible that any language would not cater for this.
This is probably the cleanest workaround:
anything="
first comment line
second comment line
"
Apart from using the overkilled way to comment multi-line codes just by installing RStudio, you can use Notepad++ as it supports the syntax highlighting of R
(Select multi-lines) -> Edit -> Comment/Uncomment -> Toggle Block Comment
Note that you need to save the code as a .R source first (highlighted in red)
I use vim to edit the R script.
Let's say the R script is test.R, containing say "Line 1", "Line 2", and "Line 3" on 3 separate lines.
I open test.R on the command line with Vim by typing "vim test.R".
Then I go to the 1st line I want to comment out, type "Control-V", down arrow to the last line I want to comment out, type a capital I i.e. "I" for insert, type "# ", and then hit the Escape key to add "# " to every line that I selected by arrowing down. Save the file in Vim and then exit Vim by typing ":wq". Changes should show up in Rstudio.
To delete the comments in Vim, start at the first line on top of the character "#" you want to delete, again do "Control-V", and arrow down to the last line you want to delete a "#" from. Then type "dd". The "#" signs should be deleted.
There's seconds-worth of lag time between when changes to test.R in Vim are reflected in Rstudio.
Now there is a workaround, by using package ARTofR or bannerCommenter
Examples here:
In RStudio an easy way to do this is to write your comment and once you have used CTRL + Shift + C to comment your line of code, then use CTRL + SHIFT + / to reflow you comment onto multiple lines for ease of reading.
In RStudio you can use a pound sign and quote like this:
#' This is a comment
Now, every time you hit return you don't need to add the #', RStudio will automatically put that in for you.
Incidentally, for adding parameters and items that are returned, for standardization if you type an # symbol inside those comment strings, RStudio will automatically show you a list of codes associated with those comment parameters:
#' #param tracker_df Dataframe of limit names and limits
#' #param invoice_data Dataframe of invoice data
#' #return return_list List of scores for each limit and rejected invoice rows