Solving syntax mistake in R - r

I am trying to run the code below with the if else statement in R :
if (check_element=="TRUE") {
sqlUpdate(uat_conn, tps00176, "integration.tps00176")
}
else {
sqlSave(uat_conn, tps00176, tablename = "integration.tps00176",rownames=TRUE,addPK=TRUE ,safer=TRUE,
varTypes = c(
"citizen"="varchar(5)",
"time"="integer",
"values"="integer"))
}
Before I run this code, else is underlined with red color with the message
unexpected token else
So can someone help me how to solve this problem and find an error in the syntax?

Related

SQLite via JDBC: SQLITE_BUSY when inserting after selecting

I'm getting the error code SQLITE_BUSY when trying to write to a table after selecting from it. The select statement and result is properly closed prior to my insert.
If I'm removing the select part the insert works fine. And this is what I'm not getting. According to the documentation SQLITE_BUSY should mean that a different process or connection (which is definetly not the case here) is blocking the database.
There's no SQLite manager running. Also jdbcConn is the only connection to the database I have. No parallel running threads aswell.
Here's my code:
try {
if(!jdbcConn.isClosed()) {
ArrayList<String> variablesToAdd = new ArrayList<String>();
String sql = "SELECT * FROM VARIABLES WHERE Name = ?";
try (PreparedStatement stmt = jdbcConn.prepareStatement(sql)) {
for(InVariable variable : this.variables.values()) {
stmt.setString(1, variable.getName());
try(ResultSet rs = stmt.executeQuery()) {
if(!rs.next()) {
variablesToAdd.add(variable.getName());
}
}
}
}
if(variablesToAdd.size() > 0) {
String sqlInsert = "INSERT INTO VARIABLES(Name, Var_Value) VALUES(?, '')";
try(PreparedStatement stmtInsert = jdbcConn.prepareStatement(sqlInsert)) {
for(String name : variablesToAdd) {
stmtInsert.setString(1, name);
int affectedRows = stmtInsert.executeUpdate();
if(affectedRows == 0) {
LogManager.getLogger().error("Error while trying to add missing database variable '" + name + "'.");
}
}
}
jdbcConn.commit();
}
}
}
catch(Exception e) {
LogManager.getLogger().error("Error creating potentially missing database variables.", e);
}
This crashes on int affectedRows = stmtInsert.executeUpdate();. Now if I remove the first block (and manually add a value to the variablesToAdd list) the value inserts fine into the database.
Am I missing something? Am I not closing the ResultSet and PreparedStatement properly? Maybe I'm blind to my mistake from looking at it for too long.
Edit: Also executing the select in a separate thread does the trick. But that can't be the solution. Am I trying to insert into the database too fast after closing previous statements?
Edit2: I came across a busy_timeout, which promised to make updates/queries wait for a specified amount of time before returning with SQLITE_BUSY. I tried setting the busy timeout like so:
if(jdbcConn.prepareStatement("PRAGMA busy_timeout = 30000").execute()) {
jdbcConn.commit();
}
The executeUpdate() function still immedeiately returns with SQLITE_BUSY.
I'm dumb.
I was so thrown off by the fact that removing the select statement worked (still not sure why that worked, probably bad timing) that I missed a different thread using the same file.
Made both threads use the same java.sql.Connection and everything works fine now.
Thank you for pushing me in the right direction #GordThompson. Wasn't aware of the jdbc:sqlite::memory: option which led to me finding the issue.

Fatal error: Can't use function return value in write context in

Fatal error: Can't use function return value in write context in /home4/tigas44/public_html/wp-content/themes/cardealer/includes/menus/menus.php on line 67
can be seen at:
http://firstnationsautomobileapproved.com/
which refers to the following line;
if(!isset($_COOKIE['cars']) || empty(json_decode($_COOKIE['cars']))) {
from the block:
$compareClass = "";
if(!isset($_COOKIE['cars']) || empty(json_decode($_COOKIE['cars']))) {
$compareClass = esc_attr(' style=display:none');
}
The empty() functions seems to be the cause of your issue. The documentation says the following:
Prior to PHP 5.5, empty() only supports variables; anything else will
result in a parse error. In other words, the following will not work:
empty(trim($name)). Instead, use trim($name) == false.
So try to change your code to this:
$compareClass = "";
if(!isset($_COOKIE['cars']) || json_decode($_COOKIE['cars']) == false) {
$compareClass = esc_attr(' style=display:none');
}

expect_error_or_warning in testthat?

I have some particularly finicky code that behaves differently on different platforms, but also behaves differently if run under valgrind ... right now I know that it
gives a warning if run on 32-bit Linux not under valgrind
gives an error if run elsewhere or on 32-bit Linux with R -d valgrind
The code below works (sorry for the lack of reproducible example, you can probably see that it would be pretty hard to write one) if I'm not running under valgrind, but under valgrind it fails because we get an error rather than a warning.
if (sessionInfo()$platform=="i686-pc-linux-gnu (32-bit)") {
expect_warning(update(g0, .~. +year), "failed to converge")
} else {
expect_error(update(g0, .~. +year), "pwrssUpdate did not converge in")
}
I would like an expect_warning_or_error() function; I suppose I could make one by hacking together the guts of expect_error and expect_warning, which don't look too complicated, but I welcome other suggestions.
Alternatively, I could figure out how to detect whether I am running under valgrind or not (seems harder).
A sort-of reproducible example:
library(testthat)
for (i in c("warning","stop")) {
expect_warning(get(i)("foo"))
expect_error(get(i)("foo"))
}
My solution, hacked together from gives_warning() and throws_error(). I'm not sure it's completely idiomatic/robust ...
gives_error_or_warning <- function (regexp = NULL, all = FALSE, ...)
{
function(expr) {
res <- try(evaluate_promise(expr),silent=TRUE)
no_error <- !inherits(res, "try-error")
if (no_error) {
warnings <- res$warnings
if (!is.null(regexp) && length(warnings) > 0) {
return(matches(regexp, all = FALSE, ...)(warnings))
} else {
return(expectation(length(warnings) > 0, "no warnings or errors given",
paste0(length(warnings), " warnings created")))
}
}
if (!is.null(regexp)) {
return(matches(regexp, ...)(res))
}
else {
expectation(TRUE, "no error thrown", "threw an error")
}
}
}
#Ben I may be misunderstanding but it comes to mind here that if you want to know if something errored/warned or not you could use tryCatch. If this is not what you want or you were hoping for a more testthat approach feel free to say, "You're way of the mark" but add an emoticon like :-) and it will make everything better.
First I make a temperamental function to mimic what you describe. Then I make an is.bad function and just look for errors or warnings (don't worry about OS as this behavior is hard to predict). Then I wrap with expect_true or expect_false:
temperamental <- function(x) {
if (missing(x)){
ifelse(sample(c(TRUE, FALSE), 1), stop("Robot attack"), warning("Beware of bots!"))
} else {
x
}
}
temperamental()
temperamental(5)
is.bad <- function(code) {
isTRUE(tryCatch(code,
error = function(c) TRUE,
warning = function(c) TRUE
))
}
expect_true(is.bad(temperamental()))
expect_false(is.bad(temperamental(5)))
I had the same problem and after reading the source for both functions I found a good solution. Actually is very simple, you only need to add a small if statement in the code from expect_error.
This is the code from expect_error
function (object, regexp = NULL, ..., info = NULL, label = NULL)
{
lab <- make_label(object, label)
error <- tryCatch({
object
NULL
}, error = function(e) {
e
})
if (identical(regexp, NA)) {
expect(is.null(error), sprintf("%s threw an error.\n%s",
lab, error$message), info = info)
}
else if (is.null(regexp) || is.null(error)) {
expect(!is.null(error), sprintf("%s did not throw an error.",
lab), info = info)
}
else {
expect_match(error$message, regexp, ..., info = info)
}
invisible(NULL)
}
Adding an if statement before the return value you check if an error was not thrown and check for warnings (remember to add the all argument to the new function). The new function code is this:
expect_error_or_warning <- function (object, regexp = NULL, ..., info = NULL, label = NULL, all = FALSE)
{
lab <- testthat:::make_label(object, label)
error <- tryCatch({
object
NULL
}, error = function(e) {
e
})
if (identical(regexp, NA)) {
expect(is.null(error), sprintf("%s threw an error.\n%s",
lab, error$message), info = info)
} else if (is.null(regexp) || is.null(error)) {
expect(!is.null(error), sprintf("%s did not throw an error.",
lab), info = info)
} else {
expect_match(error$message, regexp, ..., info = info)
}
if(is.null(error)){
expect_warning(object = object, regexp = regexp, ..., all = all, info = info, label = label)
}
invisible(NULL)
}
This code is very robust and easy to maintain. If you are writing a package and can't use functions that aren't exported (:::) you can bring the code from make_label to the function, is only one line.

How to make a test fail with the testthat package?

I have a test for which if the prerequisites are not met (e.g., missing file or something) I would like to make it fail.
Just for clarification, here's an example I'd like to do:
test_that("...", {
if ( ... precondition to execute the test is not met... ) {
expect_true(FALSE) # Make it fail without going further
}
expect_that( ... real test here ...)
})
Now my question is: Is there any fail()-like expectation in the testthat package or I have to write expect_true(FALSE) all the time?
There isn't a fail function in testthat at the moment. I think you want something like
fail <- function(message = "Failure has been forced.", info = NULL, label = NULL)
{
expect_that(
NULL,
function(message)
{
expectation(FALSE, message)
},
info,
label
)
}
Usage is, for example,
test_that("!!!", fail())
Failure is not an option...
Try using stop:
test_that("testingsomething", {
if(file.exists("foo.txt")){
stop("foo.txt already exists")
}
foo = writeFreshVersion("foo.txt")
expect_true(file.exists("foo.txt"))
}
)

how to break out of "if" block in VB.NET

How can I break out of an if statement?
Exit only works for "for", "sub", etc.
In VB.net:
if i > 0 then
do stuff here!
end if
In C#:
if (i > 0)
{
do stuff here!
}
You can't 'break out' of an if statement. If you are attempting this, your logic is wrong and you are approaching it from the wrong angle.
An example of what you are trying to achieve would help clarify, but I suspect you are structuring it incorrectly.
There isn't such an equivalent but you should't really need to with an If statement. You might want to look into using Select Case (VB) or Switch (C#) statements.
In C# .NET:
if (x > y)
{
if (x > z)
{
return;
}
Console.Writeline("cool");
}
Or you could use the goto statement.
You can use
bool result = false;
if (i < 10)
{
if (i == 7)
{
result = true;
break;
}
}
return result;
I have to admit, that in some cases you really wanna have something like an exit sub or a break. On a rare occasion is I use "Goto End" and jump over the "End If" with the def. End:
I know this is an old post but I have been looking for the same answer then eventually I figured it out
try{
if (i > 0) // the outer if condition
{
Console.WriteLine("Will work everytime");
if (i == 10)//inner if condition.when its true it will break out of the outer if condition
{
throw new Exception();
}
Console.WriteLine("Will only work when the inner if is not true");
}
}
catch (Exception ex)
{
// you can add something if you want
}
`

Resources