Ada CONSTRAINT_ERROR not being raised when it "should" - exception

I've been looking through this Ada 95 tutorial. I was reading that it is possible to define a type that has a range that is different than the standard range, and if the program tries to go outside this range it will throw an error. While working on my own program I noticed that if the end of the range in the definition falls on the boundary for of its underlying type then the program will not raise the CONSTRAINT_ERROR when assigning values out of that range. Instead it will happily keep going and then wrap around. I wrote a program to explicitly show this.
Does anyone know of an Ada rule that explains this behavior?
-Kirk
Here is the output from my terminal, the source code is below that.
me#acheron:~/Dropbox/programs/ada$ gnatmake constraints.adb -f
gcc-4.6 -c constraints.adb
gnatbind -x constraints.ali
gnatlink constraints.ali
me#acheron:~/Dropbox/programs/ada$ ./constraints
Type ON has size: 7
It has a min/max of: 0 127
It's base has a min/max of: -128 127
Type UNDER has size: 7
It has a min/max of: 0 126
It's base has a min/max of: -128 127
The value of No_Error is: 245
raised CONSTRAINT_ERROR : constraints.adb:58 range check failed
me#acheron:~/Dropbox/programs/ada$
Source Code:
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
Procedure Constraints is
type UNDER is range 0..126;
type ON is range 0..127;
type OVER is range 0..128;
Error : UNDER := 0;
No_Error : ON := 0;
Index : INTEGER := 0;
begin
New_Line;
Put("Type ON has size: ");
Put(INTEGER(ON'SIZE));
New_Line;
Put("It has a min/max of: ");
Put(INTEGER(ON'FIRST));
Put(INTEGER(ON'LAST));
New_Line;
Put("It's base has a min/max of: ");
Put(INTEGER(ON'BASE'FIRST));
Put(INTEGER(ON'BASE'LAST));
New_Line;
New_Line;
Put("Type UNDER has size: ");
Put(INTEGER(UNDER'SIZE));
New_Line;
Put("It has a min/max of: ");
Put(INTEGER(UNDER'FIRST));
Put(INTEGER(UNDER'LAST));
New_Line;
Put("It's base has a min/max of: ");
Put(INTEGER(UNDER'BASE'FIRST));
Put(INTEGER(UNDER'BASE'LAST));
Safe_Loop:
loop
No_Error := No_Error + 1;
Index := Index + 1;
--Put(INTEGER(No_Error));
exit Safe_Loop when Index = 245;
end loop Safe_Loop;
New_Line;
Put("The value of No_Error is: ");
Put(INTEGER(No_Error));
Index := 0;
Crash_Loop:
loop
Error := Error + 1;
Index := Index + 1;
exit Crash_Loop when Index = 245;
end loop Crash_Loop;
end Constraints;

According to the documentation:
Note again that -gnato is off by default, so overflow checking is not performed in default mode. This means that out of the box, with the default settings, GNAT does not do all the checks expected from the language description in the Ada Reference Manual. If you want all constraint checks to be performed, as described in this Manual, then you must explicitly use the -gnato switch either on the gnatmake or gcc command.
That said, the documentation also claims that:
Basically the rule is that in the default mode (-gnato not used), the generated code assures that all integer variables stay within their declared ranges, or within the base range if there is no declared range. This prevents any serious problems like indexes out of range for array operations. ¶ What is not checked in default mode is an overflow that results in an in-range, but incorrect value.
which seems to be wrong in the case you describe, since No_Error really does end up completely outside its range. So this seems to go beyond "not […] expected from the language description" and into the realm of "compiler bug"; but at least you should be able to fix it by adding the -gnato flag.

Related

Can I include conditional logic in VS Code snippets?

I would like to write a snippet in VS Code that writes a "switch" expression (in Javascript), but one where I can define the number of cases.
Currently there is a snippet that produces the outline of a switch expression with 1 case, and allows you to tab into the condition, case name, and the code contained within.
I want to be able to type "switch5" ("5" being any number) and a switch with 5 cases to be created, where I can tab through the relevant code within.
I know the snippets are written in a JSON file, can I include such conditional logic in this, or is it not possible?
Thanks!
The short answer is that you cannot do that kind of thing in a standard vscode snippet because it cannot dynamically evaluate any input outside of its designated variables with some limited workarounds like I'll mention next.
You might - I and others have written answers on SO about his - type your various case values first and then trigger a snippet tat would transform them into a switch statement. It is sort of doing it backwords but it might be possible.
There are extensions, however, that do allow you to evaluate javascript right in a snippet or setting and output the result. macro-commander is one such extension. I'll show another simpler extension doing what you want: HyperSnips.
In your javascript.hsnips:
snippet `switch(\d)` "add number of cases to a switch statement" A
``
let numCases = Number(m[1]) // 'm' is an array of regex capture groups
let caseString = ''
if (numCases) { // if not 'switch0'
let tabStopNum = 1
caseString = `switch (\${${tabStopNum++}:key}) {\n`
for (let index = 0; index < m[1]; index++) {
caseString += `\tcase \${${tabStopNum++}:value}:\n\t\t\$${tabStopNum++}\n`
caseString += '\t\tbreak;\n\n'
}
caseString += '\tdefault:\n'
caseString += '\t\tbreak;\n}\n'
}
rv = `${caseString}` // return value
``
endsnippet
The trickiest part was getting the unknown number of tabstops to work correctly. This is how I did it:
\${${tabStopNum++}:key}
which will resolve to ${n:defaultValue} where n gets incremented every time a tabstop is inserted. And :defaultValue is an optional default value to that tabstop. If you don't need a defaultValue just use \$${tabStopNum++} there.
See https://stackoverflow.com/a/62562886/836330 for more info on how to set up HyperSnips.

How to use Nintegrate in mathematica whose integrand contains elements from a 1d array that need to be accessed by index

I am trying to evaluate the following integral:
where the issue lies with variables like F since it is defined as
F[x_, y_] := f[x, y]/(2*Cto[Norm[x]]*Cto[Norm[y]]) and Cto[x_] := C_t[[Round[x]]]
where C_t is a 1d array and x and y are two vector and I need to access the element of C_t corresponding to the integer of the magnitude of x for example. However, this gives me the following errors when evaluating the integral:
Ci = Flatten[Import["Downloads/ctjulien.txt", "table"]]
Cp = Flatten[Import["Downloads/clphiphi.txt", "table"]]
Subscript[C, t] = Flatten[Import["Downloads/ctobs.txt", "table"]]
Lp[a_] := 1052*{Cos[a], Sin[a]}
vL[L_] := {L, 0}
l[l1_, \[CapitalPhi]1_] :=
l1*{Cos[\[CapitalPhi]1], Sin[\[CapitalPhi]1]}
Cii[x_] := Ci[[Round[x]]]
f[x_, y_] := Cii[Norm[x]]*Dot[x + y, x] + Cii[Norm[y]]*Dot[x + y, y]
Cto[x_] := Subscript[C, t][[Round[x]]]
F[x_, y_] := f[x, y]/(2*Cto[Norm[x]]*Cto[Norm[y]])
Cpp[x_] := Cp[[Round[x]]]
NIntegrate[l1*F[l[l1,\[CapitalPhi]],{L,0}-l[l1,\[CapitalPhi]]]*F[Lp[\[CapitalPhi]p],{L,0}-Lp[\[CapitalPhi]p]]*(Dot[Lp[\[CapitalPhi]p],Lp[\[CapitalPhi]p]-l[l1,\[CapitalPhi]]]*If[Norm[Lp[\[CapitalPhi]p]-l[l1,\[CapitalPhi]]]<=2900,Cpp[Norm[Lp[\[CapitalPhi]p]-l[l1,\[CapitalPhi]]]],0]*f[-{L,0}+l[l1,\[CapitalPhi]],{L,0}-Lp[\[CapitalPhi]p]]+Dot[Lp[\[CapitalPhi]p],Lp[\[CapitalPhi]p]-l[{L,0}-l[l1,\[CapitalPhi]],\[CapitalPhi]]]*If[Norm[Lp[\[CapitalPhi]p]-l[{L,0}-l[l1,\[CapitalPhi]],\[CapitalPhi]]]<=2900,Cpp[Norm[Lp[\[CapitalPhi]p]-l[{L,0}-l[l1,\[CapitalPhi]],\[CapitalPhi]]]],0]*f[-l[l1,\[CapitalPhi]],{L,0}-Lp[\[CapitalPhi]p]]),{\[CapitalPhi],-Pi,Pi},{\[CapitalPhi]p,-Pi,Pi},{l1,2,3000}]
This isn't anywhere near an answer yet, but it is a start. Watch out for Subscript and greek characters and use those appropriately when you test this.
If you insert in front of your code
Ci =Table[RandomInteger[{1,10}],{3000}];
Cp =Table[RandomInteger[{1,10}],{3000}];
Ct =Table[RandomInteger[{1,10}],{3000}];
then you can try to test your code without having your data files present.
If you then test your code you get a stream of "The expression Round[Abs[2+L]] cannot be used as a part" but if you instead insert in front of your code L=2 or some other integer assignment then that error goes away
If you use NIntegrate[yourlongexpression...] then you get a stream of "Round[Sqrt[Abs[l1 Cos[phi]]^2+Abs[l1 Sin[phi]]^2 cannot be used as a part" If you instead use fun[phi_?NumericQ, phip_?NumericQ, l1_?NumericQ]:=yourlongexpression;
NIntegrate[fun[phi,phip,l1]...] then that error goes away.
If you use Table[fun[phi,phip,l1],{phi,-Pi,Pi,Pi/2},{phip,-Pi,Pi,Pi/2},{l1,2,10}] instead of your integral and you look carefully at the output then you should see the word List appearing a number of times. That means you have somelist[[0]] somewhere in your code and Mathematica subscripts all start with 1, not with 0 and that has to be tracked down and fixed.
That is probably the first three or four levels of errors that need to found and fixed.

Set function Succ(Pascal)

How could I set in Pascal function Succ?
I mean when I put Succ in code it moves the ordinal number of character on next position. But only once. Is there way, that it could moves three times not just once?
I have found on the internet this code:
function Succ (X: ordninal_type): ordninal_type;
begin
Ord (Succ (X)) = Ord (X) + 1;
end;
My idea was to replace + 1 to + 3, but it puts me errors like:
program.lpr(6,36) Error: Identifier not found "ordninal_type"
program.lpr(19,23) Error: Incompatible type for arg no. 1: Got "Char",
expected "<erroneous type>"
So how should I set the function, so I would set it in code, like -> CHARACTER:=Succ(CHARACTER);?
'Succ' returns the successor (next value) after the current one. It can't increment more than one, because there is only one "next value".
Use Inc instead:
Inc(YourVariable, 3);
Or you can directly increment in code:
YourVariable := YourVariable + 3;
If you're dealing with a character value (data type Char), you can use Inc as well:
Ch := 'A';
Inc(Ch, 3); // Ch is now 'D'
Is that code exactly what you entered? If so, try "ordinal_type" instead of "ordninal_type"
I don't know if there are other problems here, but surely the type should be spelled correctly.

Passing variables into a function in Lua

I'm new to Lua, so (naturally) I got stuck at the first thing I tried to program. I'm working with an example script provided with the Corona Developer package. Here's a simplified version of the function (irrelevant material removed) I'm trying to call:
function new( imageSet, slideBackground, top, bottom )
function g:jumpToImage(num)
print(num)
local i = 0
print("jumpToImage")
print("#images", #images)
for i = 1, #images do
if i < num then
images[i].x = -screenW*.5;
elseif i > num then
images[i].x = screenW*1.5 + pad
else
images[i].x = screenW*.5 - pad
end
end
imgNum = num
initImage(imgNum)
end
end
If I try to call that function like this:
local test = slideView.new( myImages )
test.jumpToImage(2)
I get this error:
attempt to compare number with nil
at line 225. It would seem that "num" is not getting passed into the function. Why is this?
Where are you declaring g? You're adding a method to g, which doesn't exist (as a local). Then you're never returning g either. But most likely those were just copying errors or something. The real error is probably the notation that you're using to call test:jumpToImage.
You declare g:jumpToImage(num). That colon there means that the first argument should be treated as self. So really, your function is g.jumpToImage(self, num)
Later, you call it as test.jumpToImage(2). That makes the actual arguments of self be 2 and num be nil. What you want to do is test:jumpToImage(2). The colon there makes the expression expand to test.jumpToImage(test, 2)
Take a look at this page for an explanation of Lua's : syntax.

LINQ-to-SQL oddity with multiple where clause arguments on the same field

My problem requires me to dynamically add where clauses to a IQueryable based on user input. The problem i'm having is that Linq-to-SQL doesn't seem to like having multiple where clauses on the same field, it actually duplicates the search arg value for the last item on all parameters. I verified this behavior through a SQL trace. Here is what I'm seeing.
WHERE ([t22].[OpenText] LIKE #p11) AND ([t22].[OpenText] LIKE #p12)
-- #p11: Input NVarChar (Size = 10; Prec = 0; Scale = 0) [%classify%] // Should be 2da57652-dcdf-4cc8-99db-436c15e5ef50
-- #p12: Input NVarChar (Size = 10; Prec = 0; Scale = 0) [%classify%]
My code uses a loop to dynamically add the where clauses as you can see below. My question is how do I work around this? This pretty much seems like a bug with the tool, no?
// add dyanmic where clauses based on user input.
MatchCollection searchTokens = Helper.ExtractTokensWithinBracePairs(filterText);
if (searchTokens.Count > 0)
{
foreach(Match searchToken in searchTokens)
query = query.Where((material => material.OpenText.Contains(searchToken.Value)));
}
else
{
query = query.Where((material => material.OpenText.Contains(filterText)));
}
Closing over the loop variable considered harmful! Change
foreach(Match searchToken in searchTokens) {
query = query.Where(
material => material.OpenText.Contains(searchToken.Value)
);
}
to
foreach(Match searchToken in searchTokens) {
Match token = searchToken;
query = query.Where(
material => material.OpenText.Contains(token.Value)
);
}
You are closing over the loop variable, which is considered harmful. To fix do this:
foreach(Match searchToken in searchTokens)
{
Match searchToken2 = searchToken;
// ^^^^^^^^^^^^ copy the value of the reference to a local variable.
query = query.Where(material => material.OpenText.Contains(searchToken2.Value));
// use the copy here ^^^^^^^^^^^^
}
The reason why your version doesn't work is that the query refers to the variable searchToken, not the value it had when the query was created. When the variable's value changes, all your queries see the new value.
I don't have enough rep to leave comments yet (or this would be a comment and not an answer) but the answers listed here worked for me.
However, I had to turn off compiler optimizations in order for it to work. If you do not turn off compiler optimizations (at least at the method level) then the compiler sees you setting a loop variable to a local variable and throws the local variable away.