Catch empty ARGS in Julia - julia

I'm trying to check if there are any ARGS had been sent from the command line, using the below:
#show ARGS
localARGS = if findfirst(ARGS) == nothing ["arg1", "arg2"] else ARGS end
But got the below error:
ERROR: LoadError: syntax: space before "[" not allowed in "nothing ["
So, I recoded it as:
localARGS = if findfirst(ARGS) == nothing
["arg1", "arg2"]
else
ARGS
end
I got an error, that:
ERROR: LoadError: TypeError: non-boolean (String) used in boolean
context
I also tried:
name = (ARGS[1] == nothing ? "arg1" : ARGS[1])
But got the below error:
ERROR: LoadError: BoundsError: attempt to access 0-element
Array{String,1} at index [1]
And tried:
name = isdefined(:ARGS) ? ARGS[1] : "arg1"
But ended with below error:
ERROR: LoadError: ArgumentError: isdefined: too few arguments
(expected 2)

I found this solution using compound-expressions, and it looks to be more clean for me:
localARGS = ( if isempty(ARGS) ; ["arg1", "arg2"] ; else ARGS ; end )
For single ARGS, ternary operator can be used as:
name = isempty(ARGS) ? "arg1" : ARGS[1]

you could simply check the length of the ARGS variable:
localARGS =
if length(ARGS) == 0
["arg1", "arg2"]
else
ARGS
end
#show localARGS
Tested in Julia 0.6.4 and 1.0.0.

Related

Returning an error message other than the last one thrown in R

I have two functions that construct R S3 objects. One object encapsulates the other. When the user passes a bad num argument to fun2() it throws the error assertion in fun2(). I think it would be more informative for the user to see the message in fun1(). What are the options for preserving the message raised in fun1() and raising that instead of the message in fun2()?
fun1 <- function(num) {
assert_that(num %% 2 == 0, msg = "num should be even")
structure(num,
class = "fun1-Class"
)
}
fun2 <- function(text, num) {
assert_that(class(num) == "fun1-Class", msg = "Bad Class")
structure(list(text, num),
class = "fun2-Class"
)
}
fun1(1.2)
# Throws error "num should be even"
x <- fun2("myText", fun1(1.2))
# Throws error "Bad Class"
Traceback is below
Error: Bad Class
3.
stop(assertError(attr(res, "msg")))
2.
assert_that(class(num) == "fun1-Class", msg = "Bad Class")
1.
fun2("text", fun1(1.2))
#aurèle answered this in the comments.
This happens because of the lazy evaluation of function parameters. force(num) will change the behavior and evaluate the first constructor.

LoadError: syntax: unexpected "end" in expression starting at untitled-

I'm getting started with the Julia programming language and I'm not really understanding the "end" syntax.
function foo(s, d, m)
res = 0
for i in range(0,length(s)-m)
tmp = 0
for j in range(0,m)
tmp += s[i+m]
end
if tmp == d
res++
end
end
return res
end
Running this code I get
LoadError: syntax: unexpected "end"
in expression starting at untitled-eae5b84e07787c95497e056f34423071:10
How should I fix my function?
Julia does not increment with res++. Instead, write
res += 1

How to show error location in tryCatch?

Displaying error locations with options(show.error.locations = TRUE) doesn't seem to work when handling exceptions with tryCatch. I am trying to display location of the error but I don't know how:
options(show.error.locations = TRUE)
tryCatch({
some_function(...)
}, error = function (e, f, g) {
e <<- e
cat("ERROR: ", e$message, "\nin ")
print(e$call)
})
If I then look at the variable e, the location doesn't seem to be there:
> str(e)
List of 2
$ message: chr "missing value where TRUE/FALSE needed"
$ call : language if (index_smooth == "INDEX") { rescale <- 100/meanMSI[plotbaseyear] ...
- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
If I don't trap the error, it is printed on the console along with source file and line number. How to do it with tryCatch?
Context
As noted by Willem van Doesburg, it is not possible to use the traceback() function to display where the error occured with tryCatch(), and to my knowledge there is currently no practical way to store the position of the error with base functions in R while using tryCatch .
The idea of a separate error handler
The possible solution I found consists of two parts, the main one is writing an error handler similar to that of Chrispy from "printing stack trace and continuing after error occurs in R" which produces a log with the position of the error.
The second part is capturing this output into a variable, similarly to what was suggested by Ben Bolker in "is it possible to redirect console output to a variable".
The call stack in R seems to be purged when an error is raised and then handled (I might be wrong so any information is welcomed), hence we need to capture the error while it is occuring.
Script with an error
I used an example from one of your previous questions regarding where and R error occured with the following function stored in a file called "TestError.R" which I call in my example bellow:
# TestError.R
f2 <- function(x)
{
if (is.null(x)) "x is Null"
if (x==1) "foo"
}
f <- function(x)
{
f2(x)
}
# The following line will raise an error if executed
f(NULL)
Error tracing function
This is the function I adapted form Chrispy's code as I mentionned above.
Upon execution, if an error is raised, the code underneath will print where the error occured, in the case of the above function, it will print :
"Error occuring: Test.R#9: f2(x)" and "Error occuring: Test.R#14: f(NULL)" meaning the error result from a trouble with the f(NULL) function at line 14 which references the f2() function at line 9
# Error tracing function
withErrorTracing = function(expr, silentSuccess=FALSE) {
hasFailed = FALSE
messages = list()
warnings = list()
errorTracer = function(obj) {
# Storing the call stack
calls = sys.calls()
calls = calls[1:length(calls)-1]
# Keeping the calls only
trace = limitedLabels(c(calls, attr(obj, "calls")))
# Printing the 2nd and 3rd traces that contain the line where the error occured
# This is the part you might want to edit to suit your needs
print(paste0("Error occuring: ", trace[length(trace):1][2:3]))
# Muffle any redundant output of the same message
optionalRestart = function(r) { res = findRestart(r); if (!is.null(res)) invokeRestart(res) }
optionalRestart("muffleMessage")
optionalRestart("muffleWarning")
}
vexpr = withCallingHandlers(withVisible(expr), error=errorTracer)
if (silentSuccess && !hasFailed) {
cat(paste(warnings, collapse=""))
}
if (vexpr$visible) vexpr$value else invisible(vexpr$value)
}
Storing the error position and the message
We call the script TestError.R above and capture the printed output in a variable, here called errorStorage with which we can deal later on or simply display.
errorStorage <- capture.output(tryCatch({
withErrorTracing({source("TestError.R")})
}, error = function(e){
e <<- e
cat("ERROR: ", e$message, "\nin ")
print(e$call)
}))
Hence we keep the value of e with the call and message as well as the position of the error location.
The errorStorage output should be as follow:
[1] "[1] \"Error occuring: Test.R#9: f2(x)\" \"Error occuring: Test.R#14: f(NULL)\""
[2] "ERROR: argument is of length zero "
[3] "in if (x == 1) \"foo\""
Hoping this might help.
You can use traceback() in the error handler to show the call stack. Errors in a tryCatch don't produce line numbers. See also the help on traceback. If you use your tryCatch statements defensively, this will help you narrow down the location of the error.
Here is a working example:
## Example of Showing line-number in Try Catch
# set this variable to "error", "warning" or empty ('') to see the different scenarios
case <- "error"
result <- "init value"
tryCatch({
if( case == "error") {
stop( simpleError("Whoops: error") )
}
if( case == "warning") {
stop( simpleWarning("Whoops: warning") )
}
result <- "My result"
},
warning = function (e) {
print(sprintf("caught Warning: %s", e))
traceback(1, max.lines = 1)
},
error = function(e) {
print(sprintf("caught Error: %s", e))
traceback(1, max.lines = 1)
},
finally = {
print(sprintf("And the result is: %s", result))
})

HttpServer and Julia error with match method

I'm trying to understand how to work with this package for Julia.
Im using the following code (is an example from the package):
using HttpServer
function fibonacci(n)
if n == 1 return 1 end
if n == 2 return 1 end
prev = BigInt(1)
pprev = BigInt(1)
for i=3:n
curr = prev + pprev
pprev = prev
prev = curr
end
return prev
end
http = HttpHandler() do req::Request, res::Response
m = match(r"^/fibo/(\d+)/?$",req.resource)
if m == nothing
return Response(404)
end
number = BigInt(m.captures[1])
if number < 1 || number > 100_000
return Response(500)
end
return Response(string(fibonacci(number)))
end
http.events["error"] = (client, err) -> println(err)
http.events["listen"] = (port) -> println("Listening on $port...")
server = Server(http)
run(server, 8031)
And trying to access to the server with this link:
http://localhost:8031/fibo/100
But i get the next error:
MethodError(convert,(BigInt,"100"))
ERROR: MethodError: Cannotconvert an object of type
SubString{String} to an object of type BigInt
What im doing wrong?
I have problems to figure out what r"^/fibo/(\d+)/? does, maybe there is my problem...
You get this error because method BigInt(s::AbstractString) is deprecated and was remove in julia 0.5. Use number = parse(BigInt,m.captures[1]) instead.

Capture an uncapturable error

I want to capture an error from D%4 and move on. The error is:
Error: unexpected input in "D%4"
Typically if a function is being called the following works:
capture_warn_error <- function(x){
tryCatch({
x
}, warning = function(w) {
w
}, error = function(e) {
e
})
}
capture_warn_error(D%4)
But the no recovery is possible as `D%4 shuts down everything immediately:
## > capture_warn_error(D%4)
## Error: unexpected input in "capture_warn_error(D%4)"
Is there anyway to capture such a stubborn beast and move on? I know D%4 isn't an object but this works for other non objects:
capture_warn_error(means)
## <simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'means' not found>
It's be nice to:
Understand why D%4 is unrecoverable vs means
Find a way to recover still and capture D%4's error
As others have stated it is because text typed at the console gets passed to the parser. D%4 fails the rigid test of being valid R expression, because a single % is not valid inside an R name (although it would create a token that would be interpreted as a user defined function if there were a closing %) and % is also not a function name (although%% is). The error occurs in the processing of the argument to your function and so it never reached the internal tryCatch-call. I originally didn't get the idea that you wanted to parse this input as R code, so thought that simply wrapping readline as the single argument to be be input may satisfy:
mfun <- function( x=readline(">>+ ") ){ print(x) }
mfun()
#-----screen will display--------
>>+ D%4
[1] "D%4"
If I'm wrong about your intent, as it appears on a re-read of the question, then this would build that input mechanism into your capture_error function. This brings those characters in as unparsed text and then does the parse-eval within the tryCatch enclosure:
> capture_warn_error <- function(x=readline(">>+ ")){
+ tryCatch({ eval(parse(text=x))
+
+ }, warning = function(w) {
+ w
+ }, error = function(e) {
+ e
+ })
+ }
> capture_warn_error(D%4)
Error: unexpected input in "capture_warn_error(D%4)"
> capture_warn_error()
>>+ D%4
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: D%4
^>
> err <- capture_warn_error()
>>+ D%4
> err
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: D%4
^>
> err <- capture_warn_error()
>>+ D %% 4
> err
<simpleError in D%%4: non-numeric argument to binary operator>
> err <- capture_warn_error()
>>+ 4 %smthg% 2
> err
<simpleError in eval(expr, envir, enclos): could not find function "%smthg%">
As demonstrated above, it does require that you not provide any input in the argument list to the function call, but rather make the capture-call with an empty argument list.
You could set up a function to capture input and parse it, wrapping it in your capture_warn_error function.
getfunction <- function(){
x<-readline()
if(x == "exitnow"){return("bye!")}
print(capture_warn_error(eval(parse(text = x))))
getfunction()
}
They'll now be typing at a non-console prompt, but it will work okish - assignments will need work.
1+1
[1] 2
d%e
<simpleError in parse(text = x): <text>:1:2: unexpected input
1: d%e
^>
exitnow
[1] "bye!"
I think this works for capturing the error, although it's a bit convoluted.
a <- try(eval(parse(text="D%4")))

Resources