Global go-flag AddCommand clarification and/or example - go

In my early days of learning Go and trying to use package github.com/jessevdk/go-flags. I checked the Fly example referenced in another go-flags thread, but it apparently does not use AddCommand (at least per my grep).
The godoc article recommends defining a global parser instance and to implement each command in a separate file. Each of those command files should define a go init function which calls AddCommand on the global parser.
Making my parser global was easy enough. Confused on the init() setups:
1) My understanding is that init() order execution is random, other than your main's init running last.
2) If so, I can't ensure that my NewParser() call in my configuration code has been called prior my AddCommand() calls.
3) My code compiles, but a --help doesn't show any defined commands, making me think that indeed, the AddCommand() was called before the NewParser()
/* Just a guess */
4) QED I'm confused!
Does anybody have a recommended example I could go learn from?

Related

Clojure: capture runtime value of function arg, to use in REPL

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.

Sourcing data into rstudio [duplicate]

This is meant to be a FAQ question, so please be as complete as possible. The answer is a community answer, so feel free to edit if you think something is missing.
This question was discussed and approved on meta.
I am using R and tried some.function but I got following error message:
Error: could not find function "some.function"
This question comes up very regularly. When you get this type of error in R, how can you solve it?
There are a few things you should check :
Did you write the name of your function correctly? Names are case sensitive.
Did you install the package that contains the function? install.packages("thePackage") (this only needs to be done once)
Did you attach that package to the workspace ?
require(thePackage) (and check its return value) or library(thePackage) (this should be done every time you start a new R session)
Are you using an older R version where this function didn't exist yet?
Are you using a different version of the specific package? This could be in either direction: functions are added and removed over time, and it's possible the code you're referencing is expecting a newer or older version of the package than what you have installed.
If you're not sure in which package that function is situated, you can do a few things.
If you're sure you installed and attached/loaded the right package, type help.search("some.function") or ??some.function to get an information box that can tell you in which package it is contained.
find and getAnywhere can also be used to locate functions.
If you have no clue about the package, you can use findFn in the sos package as explained in this answer.
RSiteSearch("some.function") or searching with rdocumentation or rseek are alternative ways to find the function.
Sometimes you need to use an older version of R, but run code created for a newer version. Newly added functions (eg hasName in R 3.4.0) won't be found then. If you use an older R version and want to use a newer function, you can use the package backports to make such functions available. You also find a list of functions that need to be backported on the git repo of backports. Keep in mind that R versions older than R3.0.0 are incompatible with packages built for R3.0.0 and later versions.
Another problem, in the presence of a NAMESPACE, is that you are trying to run an unexported function from package foo.
For example (contrived, I know, but):
> mod <- prcomp(USArrests, scale = TRUE)
> plot.prcomp(mod)
Error: could not find function "plot.prcomp"
Firstly, you shouldn't be calling S3 methods directly, but lets assume plot.prcomp was actually some useful internal function in package foo. To call such function if you know what you are doing requires the use of :::. You also need to know the namespace in which the function is found. Using getAnywhere() we find that the function is in package stats:
> getAnywhere(plot.prcomp)
A single object matching ‘plot.prcomp’ was found
It was found in the following places
registered S3 method for plot from namespace stats
namespace:stats
with value
function (x, main = deparse(substitute(x)), ...)
screeplot.default(x, main = main, ...)
<environment: namespace:stats>
So we can now call it directly using:
> stats:::plot.prcomp(mod)
I've used plot.prcomp just as an example to illustrate the purpose. In normal use you shouldn't be calling S3 methods like this. But as I said, if the function you want to call exists (it might be a hidden utility function for example), but is in a namespace, R will report that it can't find the function unless you tell it which namespace to look in.
Compare this to the following:
stats::plot.prcomp
The above fails because while stats uses plot.prcomp, it is not exported from stats as the error rightly tells us:
Error: 'plot.prcomp' is not an exported object from 'namespace:stats'
This is documented as follows:
pkg::name returns the value of the exported variable name in namespace pkg, whereas pkg:::name returns the value of the internal variable name.
I can usually resolve this problem when a computer is under my control, but it's more of a nuisance when working with a grid. When a grid is not homogenous, not all libraries may be installed, and my experience has often been that a package wasn't installed because a dependency wasn't installed. To address this, I check the following:
Is Fortran installed? (Look for 'gfortran'.) This affects several major packages in R.
Is Java installed? Are the Java class paths correct?
Check that the package was installed by the admin and available for use by the appropriate user. Sometimes users will install packages in the wrong places or run without appropriate access to the right libraries. .libPaths() is a good check.
Check ldd results for R, to be sure about shared libraries
It's good to periodically run a script that just loads every package needed and does some little test. This catches the package issue as early as possible in the workflow. This is akin to build testing or unit testing, except it's more like a smoke test to make sure that the very basic stuff works.
If packages can be stored in a network-accessible location, are they? If they cannot, is there a way to ensure consistent versions across the machines? (This may seem OT, but correct package installation includes availability of the right version.)
Is the package available for the given OS? Unfortunately, not all packages are available across platforms. This goes back to step 5. If possible, try to find a way to handle a different OS by switching to an appropriate flavor of a package or switch off the dependency in certain cases.
Having encountered this quite a bit, some of these steps become fairly routine. Although #7 might seem like a good starting point, these are listed in approximate order of the frequency that I use them.
If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.
You can solve this by adding the following statement to the NAMESPACE:
exportPattern("^[^\\\\.]")
This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:
.myHiddenFunction <- function(x) cat("my hidden function")
I had the error
Error: could not find function some.function
happen when doing R CMD check of a package I was making with RStudio. I found adding
exportPattern(".")
to the NAMESPACE file did the trick. As a sidenote, I had initially configured RStudio to use ROxygen to make the documentation -- and selected the configuration where ROxygen would write my NAMESPACE file for me, which kept erasing my edits. So, in my instance I unchecked NAMESPACE from the Roxygen configuration and added exportPattern(".") to NAMESPACE to solve this error.
This error can occur even if the name of the function is valid if some mandatory arguments are missing (i.e you did not provide enough arguments).
I got this in an Rcpp context, where I wrote a C++ function with optionnal arguments, and did not provided those arguments in R. It appeared that optionnal arguments from the C++ were seen as mandatory by R. As a result, R could not find a matching function for the correct name but an incorrect number of arguments.
Rcpp Function : SEXP RcppFunction(arg1, arg2=0) {}
R Calls :
RcppFunction(0) raises the error
RcppFunction(0, 0) does not
Rdocumentation.org has a very handy search function that - among other things - lets you find functions - from all the packages on CRAN, as well as from packages from Bioconductor and GitHub.
If you are using parallelMap you'll need to export custom functions to the slave jobs, otherwise you get an error "could not find function ".
If you set a non-missing level on parallelStart the same argument should be passed to parallelExport, else you get the same error. So this should be strictly followed:
parallelStart(mode = "<your mode here>", N, level = "<task.level>")
parallelExport("<myfun>", level = "<task.level>")
You may be able to fix this error by name spacing :: the function call
comparison.cloud(colors = c("red", "green"), max.words = 100)
to
wordcloud::comparison.cloud(colors = c("red", "green"), max.words = 100)
I got the same, error, I was running version .99xxx, I checked for updates from help menu and updated My RStudio to 1.0x, then the error did not come
So simple solution, just update your R Studio

Is it really bad to use init() functions in Go?

I started a new go projects a few days ago, and I use golangci-lint to make my code in good style. I found gochecknoinits is one of linters of golangci-lint, and it tells me not to use init.
In my opinion, I can put simple initial code in init for convenience. Without init, I must write a Init function and find somewhere to call it before use that package. This can be forgotten or be done multiple times.
So, is it really bad to use init in go?
Package init() functions are a handy tool, sometimes necessary, but should not be overused. They are often used to initialize some global variables, but even global variables should be avoided as much as possible.
Quote from github.com/leighmcculloch/gochecknoinits:
Init functions cause an import to have a side effects, and side effects are hard to test, reduce readability and increase the complexity of code.
There is your answer. When you import a package, its init() functions are called and may do whatever they want to. They may change things some of your (unrelated) tests depend on, so whether your tests pass could depend on whether you import a specific package.
Further reading: Go: No globals, no init functions

c++ Hidden Unique Pointer

I have some code which depends on some include files which are partly defined at the start of source files (which is usual) and others which are used within functions.
I typical example for that are the OpenFOAM solver sources.
Because the scheme of this code is highly procedural, but I want to put all this into a class which provides init(), run() and maybe release(), I plan to put some of the variables into the classes as private making them members.
I don't want to modify the included files because they belong to a library.
The reason for using a class is that other routines classes run together with this code.
Here is the thing. init() must prepare some variable and there situations that theses variables (being type of other clases) not explicit constructors and special arguments. It is called once. run() is called several times. The procedural code has a loop only and the contents of that loop are put into the run() method.
So the best solution was to put these variables into std::unique_ptr and init can construct whatever it needs to. Obviously with that trick the variable signature changed, so I created a second declaration of a reference like this:
std::unique_ptr<volScalarField> mp_p;
volScalarField &p = *mp_p;
Now this is a bit tedious so I created a macro
FOAMPTR(volVectorField, p)
which does all the work for me:
#define FOAMPTR(TYPE,NAME) std::unique_ptr<TYPE> mp_##NAME; TYPE &NAME=*mp_##NAME
It works pretty well, but I'm not fan of macros in general, especially if you need to debug code.
Now my question is: Is there a better way to tackle this and use something else like a template definition which might do all the magic?
Edit: With 'works pretty well' I mean, that the compiler can translate that. The reference though still is invalid.
Edit: Okay, I solved the invalid pointer problem using two Macros:
#define FOAMPTR(TYPE,NAME) std::unique_ptr<TYPE> mp_##NAME
#define FETCHFOAMREF(NAME) auto &NAME=*mp_##NAME
Now I put FOAMPTR(TYPE,NAME) to the member and I get my unique ptrs. In the run() method the second macro FETCHFOAMREF(NAME) is used. Of course init() must be sure to correctly initialize the object or else the program is going to crash.
I still leave the question open because I'm not satisfied with that solution.

How can I make an external toolbox available to a MATLAB Parallel Computing Toolbox job?

As a continuation of this question and the subsequent answer, does anyone know how to have a job created using the Parallel Computing Toolbox (using createJob and createTask) access external toolboxes? Is there a configuration parameter I can specify when creating the function to specify toolboxes that should be loaded?
According to this section of the documentation, one way you can do this is to specify either the 'PathDependencies' property or the 'FileDependencies' property of the job object so that it points to the functions you need the job's workers to be able to use.
You should be able to point the way to the KbCheck function in PsychToolbox, along with any other functions or directories needed for KbCheck to work properly. It would look something like this:
obj = createJob('PathDependencies',{'path_to_KbCheck',...
'path_to_other_PTB_functions'});
A few comments, based on my work troubleshooting this:
It appears that there are inconsistencies with how well nested functions and anonymous functions work with the Parallel Computation toolkit. I was unable to get them to work, while others have been able to. (Also see here.) As such, I would recommend having each function stored in it's own file, and including those files using the PathDependencies or FileDependencies properties, as described by gnovice above.
It is very hard to troubleshoot the Parallel Computation toolkit, as everything happens outside your view. Use breakpoints liberally in your code, and the inspect command is your friend. Also note that if there is an error, task objects will contain an error parameter, which in turn will contain ErrorMessage string, and possibly the Error.causes MException object. Both of these were immensely useful in debugging.
When including Psychtoolbox, you need to do it as follows. First, create a jobStartup.m file with the following lines:
PTB_path = '/Users/eliezerk/Documents/MATLAB/Psychtoolbox3/';
addpath( PTB_path );
cd( PTB_path );
SetupPsychtoolbox;
However, since the Parallel Computation toolkit can't handle any graphics functionality, running SetupPsychtoolbox as-is will actually cause your thread to crash. To avoid this, you need to edit the PsychtoolboxPostInstallRoutine function, which is called at the very end of SetupPsychtoolbox. Specifically, you want to comment out the line AssertOpenGL (line 496, as of the time of this answer; this may change in future releases).

Resources