Friday, 1 September 2017

concept - in javascript ,apart from parameter passing in call and apply is there is any other difference where only call will work and apply can not?

i want to know the concept for call and apply uses,
Is there any execution wise difference between them.
why java script introduced call over apply?



where and when we can use call and apply in javascript?

java - How do you assert that a certain exception is thrown in JUnit 4 tests?

Update: JUnit5 has an improvement for exceptions testing: assertThrows.



following example is from: Junit 5 User Guide



 @Test

void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () ->
{
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}


Original answer using JUnit 4.




There are several ways to test that an exception is thrown. I have also discussed the below options in my post How to write great unit tests with JUnit



Set the expected parameter @Test(expected = FileNotFoundException.class).



@Test(expected = FileNotFoundException.class) 
public void testReadFile() {
myClass.readFile("test.txt");
}



Using try catch



public void testReadFile() { 
try {
myClass.readFile("test.txt");
fail("Expected a FileNotFoundException to be thrown");
} catch (FileNotFoundException e) {
assertThat(e.getMessage(), is("The file test.txt does not exist!"));
}


}


Testing with ExpectedException Rule.



@Rule
public ExpectedException thrown = ExpectedException.none();

@Test

public void testReadFile() throws FileNotFoundException {

thrown.expect(FileNotFoundException.class);
thrown.expectMessage(startsWith("The file test.txt"));
myClass.readFile("test.txt");
}


You could read more about exceptions testing in JUnit4 wiki for Exception testing and bad.robot - Expecting Exceptions JUnit Rule.

c++ - undefined reference to template function

The implementation of a non-specialized template must be visible to a translation unit that uses it.



The compiler must be able to see the implementation in order to generate code for all specializations in your code.



This can be achieved in two ways:



1) Move the implementation inside the header.



2) If you want to keep it separate, move it into a different header which you include in your original header:




util.h



namespace Util
{
template
QString convert2QString(T type , int digits=0);
}
#include "util_impl.h"



util_impl.h



namespace Util
{
template
QString convert2QString(T type, int digits=0)
{
using std::string;


string temp = (boost::format("%1") % type).str();

return QString::fromStdString(temp);
}
}

r - Add custom data label in ggplotly scatterplot




I would like to display the Species for each data point when the cursor is over the point rather than the than the x and y values. I use the iris dataset. Also I want to be able to click on a data point to make the label persistent and not get disapperaed when I choose a new spot in the plot. (if possible ). The basic is the label. The persistence issue is a plus. Here is my app:



## Note: extrafont is a bit finnicky on Windows, 
## so be sure to execute the code in the order
## provided, or else ggplot won't find the font

# Use this to acquire additional fonts not found in R
install.packages("extrafont");library(extrafont)
# Warning: if not specified in font_import, it will

# take a bit of time to get all fonts
font_import(pattern = "calibri")
loadfonts(device = "win")

#ui.r
library(shiny)
library(ggplot2)
library(plotly)
library(extrafont)
library(ggrepel)

fluidPage(

# App title ----
titlePanel(div("CROSS CORRELATION",style = "color:blue")),

# Sidebar layout with input and output definitions ----
sidebarLayout(

# Sidebar panel for inputs ----
sidebarPanel(


# Input: Select a file ----
fileInput("file1", "Input CSV-File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),

# Horizontal line ----
tags$hr(),


# Input: Checkbox if file has header ----
checkboxInput("header", "Header", TRUE),

# Input: Select separator ----
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),



# Horizontal line ----
tags$hr(),

# Input: Select number of rows to display ----
radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head")






),
# Main panel for displaying outputs ----
mainPanel(

tabsetPanel(type = "tabs",

tabPanel("Table",
shiny::dataTableOutput("contents")),
tabPanel("Correlation Plot",
tags$style(type="text/css", "
#loadmessage {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
padding: 5px 0px 5px 0px;

text-align: center;
font-weight: bold;
font-size: 100%;
color: #000000;
background-color: #CCFF66;
z-index: 105;
}
"),conditionalPanel(condition="$('html').hasClass('shiny-busy')",
tags$div("Loading...",id="loadmessage")
),

fluidRow(
column(3, uiOutput("lx1")),
column(3,uiOutput("lx2"))),
hr(),
fluidRow(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
column(3,uiOutput("td")),

column(3,uiOutput("an"))),
fluidRow(
plotlyOutput("sc"))
))
)))
#server.r
function(input, output) {


output$contents <- shiny::renderDataTable({


iris
})


output$lx1<-renderUI({
selectInput("lx1", label = h4("Select 1st Expression Profile"),
choices = colnames(iris[,1:4]),
selected = "Lex1")
})

output$lx2<-renderUI({
selectInput("lx2", label = h4("Select 2nd Expression Profile"),
choices = colnames(iris[,1:4]),
selected = "Lex2")
})

output$td<-renderUI({
radioButtons("td", label = h4("Trendline"),
choices = list("Add Trendline" = "lm", "Remove Trendline" = ""),
selected = "")

})

output$an<-renderUI({

radioButtons("an", label = h4("Correlation Coefficient"),
choices = list("Add Cor.Coef" = cor(subset(iris, select=c(input$lx1)),subset(iris, select=c(input$lx2))), "Remove Cor.Coef" = ""),
selected = "")
})



output$sc<-renderPlotly({

p1 <- ggplot(iris, aes_string(x = input$lx1, y = input$lx2))+

# Change the point options in geom_point
geom_point(color = "darkblue") +
# Change the title of the plot (can change axis titles
# in this option as well and add subtitle)
labs(title = "Cross Correlation") +
# Change where the tick marks are

scale_x_continuous(breaks = seq(0, 2.5, 30)) +
scale_y_continuous(breaks = seq(0, 2.5, 30)) +
# Change how the text looks for each element
theme(title = element_text(family = "Calibri",
size = 10,
face = "bold"),
axis.title = element_text(family = "Calibri Light",
size = 16,
face = "bold",
color = "darkgrey"),

axis.text = element_text(family = "Calibri",
size = 11))+
theme_bw()+
geom_smooth(method = input$td)+
annotate("text", x = 10, y = 10, label = as.character(input$an))
ggplotly(p1) %>%
layout(hoverlabel = list(bgcolor = "white",
font = list(family = "Calibri",
size = 9,
color = "black")))


})




}

Answer



1. Tooltip




You can change the tooltip in a number of ways, as described here. To just show Species in the tooltip, something like this should work:



library(ggplot2)
library(plotly)
p1 <- ggplot(iris, aes_string(x = "Sepal.Length",
y = "Sepal.Width",
key = "Species")) +
geom_point()
ggplotly(p1, source = "select", tooltip = c("key"))



2. Persistent Label



I'm not sure how to leave the plotly tooltip on the point upon clicking, but you could use a plotly click event to get the clicked point and then add a geom_text layer to your ggplot.



3. Minimal Example



I've adapated your code to make a simpler example. Generally, it's helpful if you create a minimal example and remove sections of your app that aren't needed to recreate your question (e.g. changing fonts).




library(shiny)
library(plotly)
library(ggplot2)

ui <- fluidPage(
plotlyOutput("iris")
)

server <- function(input, output, session) {
output$iris <- renderPlotly({

# set up plot
p1 <- ggplot(iris, aes_string(x = "Sepal.Length",
y = "Sepal.Width",
key = "Species")) +
geom_point()

# get clicked point
click_data <- event_data("plotly_click", source = "select")
# if a point has been clicked, add a label to the plot
if(!is.null(click_data)) {

label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)
p1 <- p1 +
geom_text(data = label_data,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_x = 0.25)
}
# return the plot

ggplotly(p1, source = "select", tooltip = c("key"))
})
}

shinyApp(ui, server)


enter image description here



Edit: Keep All Labels




You can store each click in a reactive data.frame using reactiveValues and use this data.frame for your geom_text layer.



library(shiny)
library(plotly)
library(ggplot2)

ui <- fluidPage(
plotlyOutput("iris")
)


server <- function(input, output, session) {
# 1. create reactive values
vals <- reactiveValues()
# 2. create df to store clicks
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
# 3. add points upon plot click
observe({

# get clicked point
click_data <- event_data("plotly_click", source = "select")
# get data for current point
label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)
# add current point to df of all clicks
vals$click_all <- merge(vals$click_all,
label_data,

all = TRUE)
})
output$iris <- renderPlotly({
# set up plot
p1 <- ggplot(iris, aes_string(x = "Sepal.Length",
y = "Sepal.Width",
key = "Species")) +
geom_point() +
# 4. add labels for clicked points
geom_text(data = vals$click_all,

aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_x = 0.25)
# return the plot
ggplotly(p1, source = "select", tooltip = c("key"))
})
}

shinyApp(ui, server)



enter image description here


jquery - How can I add/remove a class to an element when URL contains a specific string?




I have some tabs:









home

content




And I would like to add a class to the tab, when my URL contains the string ?dir.



So for example: if my URL is www.mypage.com/?dir=something then #contenttab should be active. And if the URL is for example only

www.mypage.com
then #contenttab should not be active but #hometabshould be active.



    


My script is not working. #contenttabis always active and #hometab is never active.


Answer




Try checking with this :



if ( url.indexOf( '?dir' ) !== -1 ) { ... }


Or try with :



var url = location.search; // or location.href;

if ( url.indexOf( '?dir' ) !== -1 ) { ... }


analysis - Evidence for and against the ending of Dark Knight Rises - Movies & TV

I've heard a few people mention that the ending of Dark Knight Rises, where Alfred sees Bruce and Selina at the bistro in Italy, was just a dream. When I watched it I thought it was really happening.



What evidence is there for and against this being real/imaginary?

python - How to test multiple variables against a value?



I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:




x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0 :
mylist.append("c")
if x or y or z == 1 :
mylist.append("d")
if x or y or z == 2 :

mylist.append("e")
if x or y or z == 3 :
mylist.append("f")


which would return a list of



["c", "d", "f"]



Is something like this possible?


Answer



You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:



if x == 1 or y == 1 or z == 1:


x and y are otherwise evaluated on their own (False if 0, True otherwise).



You can shorten that using a containment test against a tuple:




if 1 in (x, y, z):


or better still:



if 1 in {x, y, z}:


using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).




When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.



This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.



However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.



x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).



So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.




The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.


casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...