I have an elaborate script that spans multiple functions (and files). For debugging purposes I need to embed browser calls into all sorts of nooks and crannies. When I presumably fix something, I want to run the whole thing without debugging, ergo avoiding browser calls because commenting out all browser calls would mean a considerable effort from my part. #mdsumner on R chat suggested running the script in non-interactive mode (i.e. using Rscript.exe on Windows) but I would benefit from having that done in my console, to be able to access for instance traceback. I have gone through browser docs and I can find no option that would come close to what I'm trying to achieve. Any suggestions?
Here are three possibliities:
1) Overwrite browser command. Add this command to your global workspace to turn the browser commands off:
browser <- list
and to turn it back on
rm(browser)
This is probably the easiest but is a bit ugly due to the browser variable being left in the global environment.
The next two solutions are slightly longer but use options instead so that no new variables are introduced into the global environment. Also they are such that if no options are set then no debugging is done so you only have to set an option if you want debugging. The if solution may be faster than the expr solution although its likely not material.
2) Use expr= argument with option. Replace each browser command with:
browser(expr = isTRUE(getOption("Debug")))
and then define the "Debug" option to be TRUE to turn debugging on.
options(Debug = TRUE)
or set it to something else or remove it to turn debugging off:
options(Debug = NULL)
3) Use if with an option. Replace each browser command with:
if (isTRUE(getOption("Debug"))) browser()
and then set the Debug option or not as in the prior point.
Define global logical value
debug_mode <- TRUE
and then instead of browser() use
if (debug_mode) browser()
I think this just comes down to nuanced use of a debugging function. If you want to selectively control the use of browser(), put it inside an if that lets you enable or disable debugging for the function. When you want browser to be called, make that explicit like
myfun(x, debug = TRUE)
Related
Problem
My web front-end calls back-end queries with complex arguments. During development, to avoid time-consuming manual replication of those arguments, I want to capture their values in Vars, which can be used in REPL.
Research
This article shows that inline def is a suitable solution, but I couldn't make it work. After a call from the front-end happened, the Var remained unbound.
I launched the backend with REPL through VS Code + Calva, with the following code:
(defn get-analytics-by-category [params]
(def params params)
...)
And here's the evaluation of the Var in the REPL:
#object[clojure.lang.Var$Unbound 0x1298f89e "Unbound: #'urbest.db.queries/params"]
Question
Why the code above didn't bound value of the argument to the Var? Is there another solution?
The best way that I found is to use scope-capture library. It captures all the local variables with addition of 1 line in a function, and then with another 1-liner you can define all those variables as global, which allows you to evaluate in REPL any sub-expression in the function using runtime values.
If you ever spent a lot of time reproducing complex runtime values, I strongly recommend watching their 8-min demo.
My issue with inline-def was likely caused by reloading namespace after the Var was bound to a value. After restarting VS Code and carefully doing everything again, the issue went away.
Another way to look at the runtime is to use a debugger.
It is more flexible than scope-capture, but requires a bit more work to make variables available outside an execution.
VS Code's Calva extension comes with one, there's also Emacs packages.
I have a lot of old Perl code that gets called frequently, I have been writing a new module and all of a sudden I'm getting a lot of warnings in my error_log for Apache, they are for every module currently being used. e.g,
"my" variable $variable masks earlier declaration in same statement at
/path/to/module.pm line 40 (#1)
Useless use of hash element in void context at
/path/to/another/module.pm line 212 (#2)
The main layout of the codebase is one giant script that includes the modules and directs the requests to them needed to create certain pages for the website and the main script then handles static elements like menus.
My current project is separated from this main script and doesn't use it however any time I call my code using ajax, there are some other ajax calls that will use the main script and the warnings only seem to appear from those request but only when I'm calling my project.
I have grepped every module and none of them have use warnings (or -w) in them, I have also tried using no warnings 'all' in the main script and my own project but it's not doing anything.
At this point I'm out of ideas on what to do next so all help is appreciated, I'd just like to suppress the warnings, the codebase is quite old and poorly written so going and correcting each issue that causes the warns in the first place isn't do-able.
The Apache server is running mod_perl as well, if that might make a difference I have a feeling it might be something to do with CGI, but I can't seem to find any evidence.
I take it that the code gets called by running certain top-level Perl script(s).
Then use the __WARN__ hook in those script(s) to stop printing of warnings
BEGIN { $SIG{__WARN__} = sub {} };
Place this BEGIN block before the use statements so to affect modules as well.
An empty subroutine is the way to mute warnings since __WARN__ doesn't support 'IGNORE'.
See warn and %SIG in perlvar.
See this post and this post for comments and some examples.
To investigate further and track the warnings you can use Carp
BEGIN {
$SIG{__WARN__} = \&Carp::cluck; # or Carp::confess; to also die
}
which will make it print full stack traces. This can be fine-tuned as you please since we can write our own sub to be called. Or use Carp::Always.
See this post
for some more drastic measures (like overriding CORE::GLOBAL::warn)
Once you find a more precise level at which to suppress warnings then local $SIG{__WARN__} is the way to go, if possible. This is used in a post linked above, and here is another example. It is of course far better to suppress warnings only where needed instead of everywhere.
More detail
Getting stack traces in Perl?
How can I get a call stack listing in Perl?
Note that longmess is unfortunately no longer so standard and well supported.
Simple question. I'd like to know how to tell whether the current shell is running as a mc subshell or not. If it is, I'd like to enter a degraded mode without some features mc can't handle.
In particular, I'd like this to
Be as portable as possible
Not rely on anything outside the shell and basic universal external commands.
Though it's not documented in the man page, a quick experiment shows that mc sets two environment variables: $MC_TMPDIR and $MC_SID. (It also sets $HISTCONTROL, but that's not specific to mc; it affects the behavior of bash, and could have been set by something other than mc.)
If you don't want to depend on undocumented features, you can always set an environment variable yourself. For example, in bash:
mc() { MC_IS_RUNNING=1 command mc "$#" ; }
Entering a "degraded mode" is another matter; I'm not sure how you'd do that. I don't know of any way in bash to disable specified features. You could disable selected built-in commands by defining functions that override them. What features do you have in mind?
I want to watch the flow the execution of my ruby code when I am in the console. For example, if I have this :
def process
hash = {a:1,b:2}
hash.values.map!{|e| e+1}
end
And I want to see something like this in console when I type process :
hash = {a:1,b:2}
=> {:a=>1, :b=>2}
hash.values.map!{|e| e+1}
=> [2, 3]
Is there a useful way to do something like this?
$VERBOSE doesn't seems to do anything and $DEBUG seems as the opposite to be too verbose.
You're talking about "trace" functionality.
Some languages, like shell and good-ol' GWBasic, have a flag to show their currently executing line. Ruby's $DEBUG output can flood you with information overload, not so much from your code, but from any gems that look for it and dump their current state or turn on their tracing.
Many people sprinkle their code with puts to have it show some indicator of where they are, during their development/testing. If you do that, I'd recommend writing it as a method to bottleneck your output and let you easily turn it on/off. Also, use a flag to check whether you want to debug. You might even want to use OptionParser to let you create a --debug flag to pass on the command-line. Another nice side-effect of using a method is it's easy to redirect the output to a file you can tail and watch the output as it occurs, and later use for triage.
Another alternative is to load the code into the debugger and tell it to trace. You'll see every step of the code, which is very verbose, but the detail is good. You can also tell it to run to certain points so you can poke at the code and dig around, dropping into IRB if needed.
Personally, being old-school and having cut my teeth on assembly-language, I'm comfortable in debuggers, so I use Ruby's a lot. It's easy to tell it to run to a certain spot and stop, or you can embed include 'debugger'; debugger into your code and it'll stop at that point. Once there, it's possible to see what's going on, then c to continue, and let the program run until it hits the debugger statement again. I find the debugger to be very powerful and a nice selective magnifying glass for those times I want to know what's going on.
"Debugging in Ruby" has lots of nice tips you might find useful too.
EDIT:
I like Alex D's suggestion to look into Ruby's set_trace_func. I haven't used it (and, frankly forgot about it), but that'd be a good way to set up a nice trace in an app. With a little code you could set up toggling it on/off and selectively outputting given a certain class or condition since you're in control of the proc being called.
One option would be to use set_trace_func (http://apidock.com/ruby/Kernel/set_trace_func) to set up a hook which will print out each line as it is executed. Be aware that may overwhelm you with a bunch of information on the internals of irb.
Another option would be to dig into the source code for irb and add an option to print each line as it is executed.
Have you tried the pry gem? Put require 'pry'; binding.pry inside your code and run your script. You will have a ruby console just where your put it. Maybe that is what you are looking for.
Otherwise you should take a look at a ruby debugger.
Say I have some function foo that is used in a standalone application, (ie. compiled into an executable with mcc -m,) which has an important intermediate result bar. Normally I don't need this intermediate result after completion of the function and thus it is not a return value. However for development and debugging purposes it is useful to be able to make this intermediate result accessible, which I may do by using assignin to put the intermediate result in some debug workspace.
Now the problem is that the assignin isn't possible in a standalone compilation and mcc will complain with an error if there is an assignin in the code. What I'd like to do is include the assignin only when the code is run interactively and not when being compiled as a standalone application. Additionally, this would speed things up as I would not need the intermediate result anyway in the standalone application and thus can same time and/or memory by not doing the assignin in the standalone application. In any other programming environment one would call this compiling in debug and release mode.
In pseudo-matlab:
function res = foo()
bar = some complicated formula
if ~standalone
assignin('debug', 'foo_bar', bar)
end
res = some complicated formula involving bar
The problem is that I know of no way of expressing the if ~standalone, firstly I don't know how to test for being in standalone mode or not, but more crucially, this needs to be some code construct that actually causes mcc to completely disregard the guarded code block and not try to compile it, because the assignin can not be compiled in standalone mode.
As an aside, this would not just be valuable for intermediate results, but also for extra data gathering, where extra data would be calculated in the guarded block and exported by way of an assignin. Obviously such extra data should not be calculated in the standalone version as it would not serve any purpose.
Is there any such code construct in matlab that would allow for this to be done, or is there a better alternative? Up to now I've just been juggling commented code, uncommenting and recommenting the debug code as I went along in the development process.
Instead of using assignin to populate a debug workspace, you could use a global debugging struct and stash the variables in fields of the same name. All valid variable names are also valid struct field names. You could implement this with a global variable, but would probably be better done with a persistent variable inside a function. This will work in compiled or non-compiled code.
First, have a function that defines your debugging mode.
function out = isdebugging(value)
%ISDEBUGGING Get or set the global debugging state
persistent state
if isempty(state)
state = false;
end
switch nargin
case 0 % Getter
out = state;
case 1 % Setter
state = value;
end
Then a function for stashing the debugging values, that only holds on to values when debug mode is on.
function out = debugval(action, name, value)
%DEBUGVAL Stash values for debugging
persistent stash
if isempty(stash)
stash = struct;
end
% Short-circuit when not in debugging mode to save space
if ~isdebugging()
return;
end
switch action
case 'get'
out = stash.(name);
case 'getall'
out = stash;
case 'set'
stash.(name) = value;
case 'list'
out = fieldnames(stash);
case 'remove'
stash = rmfield(stash, name);
case 'clear'
stash = struct;
end
The debugging is disabled by default so it will short-circuit in the compiled version and not accumulate values. Enable it manually in your interactive Matlab session with isdebugging(true). This bypasses the issue of detecting whether you're running deployed. It also means you can enable and use it in your compiled app, if you want to test the compiled code to see how it's working in that context. You can use a GUI button or environment variable to tell the compiled app to enable debugging.
The isdebugging() call can guard other code. But I wouldn't get too carried away with using isdebugging() to guard anything besides log output or value accumulation. You don't want your debugging mechanism to have side effects on the correctness of your code.
Also have a look at Java's log4j as a model of how to incorporate run-time configurable debugging output in an application. You could apply its principles to Matlab.
Use the function isdeployed. isdeployed is true when run in the MCR, and false when run in MATLAB.
EDIT: Of course, this doesn't solve the problem of compiling. You might have to find a substitute for assignin..