armadillo how to get rid of error message - armadillo

Running the following code still produces an error message that goes to stdout (not stderr) although the exception was successfully caught:
Mat<double> matrix_quantiles(const vector<double> & quantiles,
const Mat<double> & m) {
Mat<double> sorted_matrix;
try {
sorted_matrix = arma::sort(arma::cor(m));
} catch(std::logic_error & e) {
/*
Sometimes a col is constant, causing the correlation to be
infinite. If that happens, add normal random jitter to the
values and retry.
*/
const Mat<double> jitter = Mat<double>(
m.n_rows, m.n_cols, arma::fill::randn);
return matrix_quantiles(quantiles, 1.e-3 * jitter + m);
}
etc.
The error message is:
error: sort(): given object has non-finite elements
The code runs fine, and the jittering strategy is good enough for what I do, but I have to filter out the error message if I write the output to stdout.
Thank you.

To disable printing of error messagaes, define a macro named ARMA_DONT_PRINT_ERRORS before including the Armadillo header. For example:
#define ARMA_DONT_PRINT_ERRORS
#include <armadillo>

Related

"memory allocation error: block too big" doing simple integer division

I have a weird issue. LUA 5.3.5, compiled on STM32F429. Free RAM is about 1Mb (memory allocation is using external SDRAM, not the more limited internal RAM on the STM32). Note that working with things like strings works fine, as well. It only seems to be division causing the problem.
This script works:
a=100
b=20
c=a+b
print(c)
This script returns "memory allocation error: block too big:"
a=100
b=20
c=a/b
print(c)
Further research is showing that the problem is not with the division, at all. It is with tostring() which is called by print(). For some reason, tostring() is trying to allocate too much memory when dealing with the result from direct division.
In lstring.c, is the following:
luaS_newlstr():
if (l >= (MAX_SIZE - sizeof(TString))/sizeof(char))
luaM_toobig(L);
When the issue occurs, l == 0xd0600f56
(interestingly, that is a memory address location in the range of the external SDRAM, rather than a valid string size).
If I modify the LUA script to do the following, it works fine:
a=100
b=20
c=math.floor(a/b)
print(c)
I checked and in both cases, c is type==number
As for the question regarding the memory allocation, we are using the dlmalloc() library, configured like this during LUA startup:
ezCmdLua = lua_newstate(ezlua_poolalloc, NULL);
int error = luaL_loadbuffer(ezCmdLua, bfr, len, "ezCmdLua");
if (!error)
{
error = lua_pcall(ezCmdLua, 0, 0, 0);
if (error) {
...
}
}
....
static void *ezlua_poolalloc (void *ud, void *ptr, size_t osize, size_t nsize) {
(void)ud; (void)osize; /* not used */
if (nsize == 0) {
dlfree(ptr);
return NULL;
}
else
return dlrealloc(ptr, nsize);
}
I have confirmed that memory allocation is working properly, and I can do things like string manipulation and printing of strings with no problem at all. In fact, when debugging this issue, the luaS_newlstr() function is called several times prior to the issue occurring, and each time l (the length of the string) is a reasonable value. That is, until I try to print the result of the division. Moving the division around in the script makes no difference (ie, adding things before it like other print statements), so I doubt the stack is being trashed.

Is there a way to print a console message with Flutter?

I'm debugging an app, but I need to know some values in the fly, I was wondering if there's a way to print a message in console like console.log using Javascript.
I appreciate the help.
print() is probably what you are looking for. Here's some more info on debugging in flutter.
You can use
print()
function or
debugPrint()
The debugPrint() function can print large outputs.
There are more helpful methods in import 'dart:developer' library and one of them is log().
example:
int i = 5;
log("Index number is: $i");
//output
[log] Index number is: 5
void log(String message, {DateTime time, int sequenceNumber, int level
= 0, String name = '', Zone zone, Object error, StackTrace stackTrace})
Emit a log event.
This function was designed to map closely to the logging information
collected by package:logging.
[message] is the log message
[time] (optional) is the timestamp
[sequenceNumber] (optional) is a monotonically increasing sequence number
[level] (optional) is the severity level (a value between 0 and 2000); see the package:logging Level class for an overview of the
possible values
[name] (optional) is the name of the source of the log message
[zone] (optional) the zone where the log was emitted
[error] (optional) an error object associated with this log event
[stackTrace] (optional) a stack trace associated with this log event
Read more.:
print() is from dart:core and its implementation:
/// Prints a string representation of the object to the console.
void print(Object object) {
String line = "$object";
if (printToZone == null) {
printToConsole(line);
} else {
printToZone(line);
}
}
debugPrint():
/// Prints a message to the console, which you can access using the "flutter"
/// tool's "logs" command ("flutter logs").
///
/// If a wrapWidth is provided, each line of the message is word-wrapped to that
/// width. (Lines may be separated by newline characters, as in '\n'.)
///
/// By default, this function very crudely attempts to throttle the rate at
/// which messages are sent to avoid data loss on Android. This means that
/// interleaving calls to this function (directly or indirectly via, e.g.,
/// [debugDumpRenderTree] or [debugDumpApp]) and to the Dart [print] method can
/// result in out-of-order messages in the logs
// read more here: https://api.flutter.dev/flutter/foundation/debugPrint.html
DebugPrintCallback debugPrint = debugPrintThrottled;
/// Alternative implementation of [debugPrint] that does not throttle.
/// Used by tests.
debugPrintSynchronously(String message, { int wrapWidth })
/// Implementation of [debugPrint] that throttles messages. This avoids dropping
/// messages on platforms that rate-limit their logging (for example, Android).
void debugPrintThrottled(String message, { int wrapWidth })
Read more.
Note that only the print() is taking any type and print to the console. debugPrint() and log() only take String. So, you have to add .toString() or use string interpolation like I shown in provided example snippet.
I tend to do something similar to this
Foo foo;
try{
foo = _someMethod(); //some method that returns a new object
} catch (e) {
print('_someMethod: Foo Error ${foo.id} Error:{e.toString()}'); /*my custom error print message. You don't need brackets if you are printing a string variable.*/
}
Use debug print to avoid logging in production application.
debugPrint("Message");
You can also disable or change debug print implementation in main.dart or any other file like this:
debugPrint = (String message, {int wrapWidth})
{
debugPrintThrottled(message);//Or another other custom code
};
print, debugPrint and others have got some word limit restrictions, if you have something long to print on console, you can:
Create this method:
void printWrapped(String text) {
final pattern = RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
Usage:
printWrapped("Your very long string ...");
Source
One more answer for Concatenate with String:
// Declaration
int number = 10;
//Button Action
RaisedButton(
child: Text("Subtract Me"),
onPressed: () {
number = number - 1;
print('You have got $number as result');
print('Before Value is ${number - 1} and After value is ${number + 1}');
},
),
//Output:
flutter: You have got 9 as result
flutter: Before Value is 8 and After value is 10
debugPrint()
Might as well use rather than print() as it attempts to reduce log line drop or being out of order on Android kernel
Refs:
Logging in Flutter
I think this might help you, because, I was also got stuck in many ways of knowing the output of my code in the dart file, hence I got the solution by following the steps, shown in the video.
https://www.youtube.com/watch?v=hhP1tE-IHos
here I have shown an instance of how it works after following the video.
check the left side column where it shows about the value which profile variable carry i.e., null
you can simply use print('whatever you want to print') same as console.log() in javascript.
for more info you can check here.
Note that the print() and log() options both add their own labels at the start of the line, and apply additional formatting that can cause long lines to be truncated. In the case of a dart:io app, you can bypass this interception and mangling entirely by going directly to stdout/stderr, etc. as in stdout.write(), stdout.writeln(), etc. Likewise if you are looking to log explicitly to one or the other. I ran into this issue when adding CLI args to a flutter application.
I use something like this. The print() function can print data up to some limit. So I use this log.
import 'dart:developer';
debugLog({String tag = '', required dynamic value}) {
log("TAG $tag : ${value.toString()}");
}

How can I read input after the wrong type has been entered in D readf?

I am wondering how to continue using stdin in D after the program has read an unsuitable value. (for example, letters when it was expecting an int)
I wrote this to test it:
import std.stdio;
void main()
{
int a;
for(;;){
try{
stdin.readf(" %s", a);
break;
}catch(Exception e){
writeln(e);
writeln("Please enter a number.");
}
}
writeln(a);
}
After entering incorrect values such as 'b', the program would print out the message indefinitly. I also examined the exception which indicated that it was trying to read the same characters again, so I made a version like this:
import std.stdio;
void main()
{
int a;
for(;;){
try{
stdin.readf(" %s", a);
break;
}catch(Exception e){
writeln(e);
writeln("Please enter a number.");
char c;
readf("%c", c);
}
}
writeln(a);
}
Which still threw an exception when trying to read a, but not c. I also tried using stdin.clearerr(), which had no effect. Does anyone know how to solve this? Thanks.
My recommendation: don't use readf. It is so bad. Everyone goes to it at first since it is in the stdlib (and has been since 1979 lol, well scanf has... and imo i think scanf is better than readf! but i digress), and almost everyone has trouble with it. It is really picky about formats and whitespace consumption when it goes right, and when it goes wrong, it gives crappy error messages and leaves the input stream in an indeterminate state. And, on top of that, is still really limited in what data types it can actually read in and is horribly user-unfriendly, not even allowing things like working backspacing on most systems!
Slightly less bad than readf is to use readln then strip and to!int it once you check the line and give errors. Something like this:
import std.stdio;
import std.string; // for strip, cuts off whitespace
import std.algorithm.searching; // for all
import std.ascii; // for isAscii
import std.conv; // for to, does string to other type conversions
int readInt() {
for(;;) {
string line = stdin.readln();
line = line.strip();
if(all!isDigit(line))
return to!int(line);
else
writeln("Please enter a number");
}
assert(0);
}
void main()
{
int a = readInt();
writeln(a);
}
I know that's a lot of import spam (and for a bunch of individual trivial functions too), and readln still sucks for the end user, but this little function is going to be so much nicer on your users and on yourself than trying to use readf. It will consistently consume one line at a time and give a nice message. Moreover, the same pattern can be extended to any other type of validation you need, and the call to readln can be replaced by a call to a more user-friendly function that allows editing and history and stuff later if you decide to go down that route.
If you must use readf anyway though, easiest way to make things sane again in your catch block is still to just call readln and discard its result. So then it just skips the whole line containing the error, allowing your user to start fresh. That'd also drop if they were doing "1 2" and wanted two ints to be read at once... but meh, I'd rather start them fresh anyway than try to pick up an errored line half way through.

How can I determine if user's input is empty?

I am writing code to generate a JavaCC parser, which will read a user's input and check if it is in any one of a set of languages defined in my code.
One condition on allowable input is that it must not be empty - i.e., the user must enter some block of characters (with length greater than or equal to 1) other than white space " ".
I would like to be able to determine if the user's input is empty, so that an error message can be printed out on the screen in that case.
I have written a production (a.k.a rule) that gets the user's input; it's called Input() and is declared to be void.
In the main method, I have tried to write code which determines if the user's input is empty, by writing:
if parser.Input() == null {
// print error message onto the screen
}
However, I get an error message on the terminal when I try to compile, stating that a 'void' type is not allowed here (I am sure this is referring to Input).
Could I please have a hint/hints for getting around this issue?
Write the Input production like this
boolean Input() : {
} {
<EOF>
{return true;}
|
... // other possibilities here
{return false;}
}
Then, in the main method, you can write
if( parser.Input() ) {
... // report error
}
This solves the problem of reporting the error.
However you may also want to report the language found. For that you could make an enumeration type and have Input return a member of the enumeration. EMPTY could be one of the possibilities.
Language lang = parser.Input() ;
switch( lang ) {
case EMPTY:
... // report error
break ;
case LANGA:
...
break ;
... // etc.
}
Change your type method so this can return a value and you can validate the result, when you do this but change the comparison like this:
if null==parser.Input(){
//print error message on screen
}
Another option is to validate data inside your Input method so you keep it like void.

luaL_dostring() crashes when given script has syntax error

i try to integrate Lua in a embedded project using GCC on a Cortex-M4. i am able to load and run a Lua script, calling Lua functions from C, calling C functions from Lua. but the C program crashes (HardFault_Handler trap rises) when the given script passed as parameter in luaL_dostring() contains any Lua syntax errors.
here the relevant C code that crashes due to the syntax error in Lua:
//create Lua VM...
luaVm = lua_newstate(luaAlloc, NULL);
//load libraries...
luaopen_base(luaVm);
luaopen_math(luaVm);
luaopen_table(luaVm);
luaopen_string(luaVm);
//launch script...
luaL_dostring(luaVm, "function onTick()\n"
" locaal x = 7\n" //syntax error
"end\n"
"\n" );
when doing the same with correct Lua syntax, then it works:
luaL_dostring(luaVm, "function onTick()\n"
" local x = 7\n"
"end\n"
"\n" );
when debugging and stepping through luaL_dostring(), i can follow the Lua parsing line for line, and when reaching the line with the syntax error, then the C program crashes.
can anybody help? thanks.
have disabled setjmp/longjmp in Lua source code in the following way:
//#define LUAI_THROW(L,c) longjmp((c)->b, 1) //TODO oli4 orig
//#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } //TODO oli4 orig
#define LUAI_THROW(L,c) while(1) //TODO oli4 special
#define LUAI_TRY(L,c,a) { a } //TODO oli4 special
...so there is no setjmp/longjmp used anymore, but i still have the crash :-(
must have another cause???
found the problem: it is the sprintf function called on Lua syntax error. in fact, on my platform sprintf seems not support floating point presentation. so i changed luaconf.h the following way, limiting the presentation to integer format.
//#define LUA_NUMBER_FMT "%.14g"
#define LUA_NUMBER_FMT "%d"
must have another cause???
Yes: you can't use Lua here.
Lua's error handling system is built on a framework of setjmp/longjump. You can't just make LUAI_THROW and LUAI_TRY do nothing. That means lua_error and all internal error handling stops working. Syntax errors are part of Lua's internal error handling.
If your C compiler doesn't provide proper support for the C standard library, then Lua is simply not going to be functional in that environment. You might try LuaJIT, but I doubt that will be any better.
#define LUAI_THROW(L,c) c->throwed = true
#define LUAI_TRY(L,c,a) \
__try { a } __except(filter()) { if ((c)->status == 0 && ((c)->throwed)) (c)->status = -1; }
#define luai_jmpbuf int /* dummy variable */
struct lua_longjmp {
struct lua_longjmp *previous;
luai_jmpbuf b;
volatile int status; /* error code */
bool throwed;
};
Works as expected even you build without C++ exceptions

Resources