number(X) as function parameter or return value generates PLS 00103 error - function

I have the following function definition:
create or replace FUNCTION checkXML
(idx in number(19))
return number(19)
is
...
But when I compile it, am getting the following errors,
Error(2,16): PLS-00103: Encountered the symbol "(" when expecting one of the
following: := . ) , # % default character The symbol ":=" was substituted for
"(" to continue.
Error(3,15): PLS-00103: Encountered the symbol "(" when expecting one of the
following: . # % ; is authid as cluster order using external character
deterministic parallel_enable pipelined aggregate result_cache

Change the function declaraction to be
create or replace FUNCTION checkXML
(idx in number)
return number
PL/SQL doesn't accept length or precision specifiers on parameters or return types.
Share and enjoy.

Related

Maxima add current loop iteration to filename

I have code similar to the one below, where a function with a parameter depending on the loop iteration is plotted after every iteration. I would like to save the plot with the name trigplot_i.ps where i is the iteration number, but don't know how.
I have tried trigplot_"i".ps but didn't work, and have not been able to find how to cast i to a string either.
I'm a beginner so any help is very welcome.
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10 do
(plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file,"./trigplot_i.ps"],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
code after edits gives an error:
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10
do block([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", myfile),
plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file, myfile],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
error:
"declare: argument must be a symbol; found "./trigplot_1.ps
-- an error.
To debug this try: debugmode(true);"
Looks good. To construct a file name, try this: sconcat("./trigplot_", i, ".ps") or also you can try: printf(false, "./trigplot_~d.ps", i). My advice is to make that a separate step in the loop, and then you can use it in the call to plot2d, e.g.:
for i:1 thru 10
do block ([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", i, myfile),
plot2d (<stuff goes here>, [ps_file, myfile], <more stuff>));
EDIT: Fixed a bug in printf (omitted argument i).

Function of function(functional) in Maxima

I want to define a function of a function ( maybe functional) in Maxima. For example, I want to define T in the code:
f(r,GN,M)::=(2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2);
X(r,GN,M) ::= 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r));
T(r,GN,M) ::= diff(f(r,GN,M),r)+X(r,GN,M);
But I don't know the code.
In maxima it is convenient to use expressions.
Define two expressions
(%i1) display2d: false $
(%i2) f: (2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2) $
(%i3) X: 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r)) $
Define a function which operates on two expressions
(%i4) T(f, X) := diff(f, r) + X $
Call it. Result is an expression
(%i5) dfpX: T(f, X);
(%o5) (2*GN*M*(1-(GN*M)/(2*r)))/r+(GN*M)/r+2*GN*M^2
*((2*GN^2*M^2)/r^3-(2*GN*M)/r^2)
You can create a function based on dfpX
(%i6) define(f(r, GN, M), dfpX);
(%o6) f(r,GN,M):=(2*GN*M*(1-(GN*M)/(2*r)))/r+(GN*M)/r
+2*GN*M^2*((2*GN^2*M^2)/r^3-(2*GN*M)/r^2)
and call it
(%i7) f(1, 2, 3);
(%o7) 2142
but you can stay with expressions
(%i8) subst([r=1, GN=2, M=3], dfpX);
(%o8) 2142
Define T as a function, rather than a macro, so that it evaluates its arguments.
(%i) T(r,GN,M) := diff(f(r,GN,M),r)+X(r,GN,M)$
Now define a function t on T which quotes ' its arguments (so that T knows which variable to differentiate with respect to) and then evaluates the result %% with ev.
(%i) t(r,GN,M) := (T('r,'GN,'M),ev(%%))$
(%i) t(1,2,3);
(%o) 2142

Program Works in Python 2.7, but not Python 3.3 (Syntax is compatible for both)

So I have the function integral(function, n=1000, start=0, stop=100) defined in nums.py:
def integral(function, n=1000, start=0, stop=100):
"""Returns integral of function from start to stop with 'n' rectangles"""
increment, num, x = float(stop - start) / n, 0, start
while x <= stop:
num += eval(function)
if x >= stop: break
x += increment
return increment * num
However, my teacher (for my Programming class) wants us to create a separate program that gets the input using input() and then returns it. So, I have:
def main():
from nums import integral # imports the function that I made in my own 'nums' module
f, n, a, b = get_input()
result = integral(f, n, a, b)
msg = "\nIntegration of " + f + " is: " + str(result)
print(msg)
def get_input():
f = str(input("Function (in quotes, eg: 'x^2'; use 'x' as the variable): ")).replace('^', '**')
# The above makes it Python-evaluable and also gets the input in one line
n = int(input("Numbers of Rectangles (enter as an integer, eg: 1000): "))
a = int(input("Start-Point (enter as an integer, eg: 0): "))
b = int(input("End-Point (enter as an integer, eg: 100): "))
return f, n, a, b
main()
When run in Python 2.7, it works fine:
>>>
Function (in quotes, eg: 'x^2'; use 'x' as the variable): 'x**2'
Numbers of Rectangles (enter as an integer, eg: 1000): 1000
Start-Point (enter as an integer, eg: 0): 0
End-Point (enter as an integer, eg: 100): 100
Integration of x**2 is: 333833.5
However, in Python 3.3 (which my teacher insists we use), it raises an error in my integral function, with the same exact input:
Traceback (most recent call last):
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 20, in <module>
main()
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 8, in main
result = integral(f, n, a, b)
File "D:\my_stuff\Google Drive\Modules\nums.py", line 142, in integral
num += eval(function)
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
In addition, integral by itself (in Python 3.3) works fine:
>>> from nums import integral
>>> integral('x**2')
333833.4999999991
Because of that, I believe the fault is in my program for my class... Any and all help is appreciated. Thanks :)
The issue you're running into is that input works differently in Python 2 and Python 3. In Python 3, the input function works like the raw_input does in Python 2. Python 2's input function is equivalent to eval(input()) in Python 3.
You're getting into trouble because of the quoteation marks you're typing with the formula. When you type 'x**2' (with the quotes) as your formula when running on Python 2, the text gets evaled in the input function and you get a string with no quotation marks as the result. This works.
When you give the same string to Python 3's input function, it doesn't do an eval, so the quotation marks remain. When you later eval the formula as part of your integral calculation, you get the string x**2 (without any quotation marks) as the result, not the value of x squared. This results in an exception when you try the string to 0.
To fix this, I suggest either using just one version of Python, or putting the following code at the top of your file to get a Python 3 style input in both versions:
# ensure we have Python 3 semantics from input, even in Python 2
try:
input = raw_input
except NameError:
pass
Then just type in your formula without quotation marks and it should work correctly.

SQL Scripts - Does the equivalent of a #define exist?

I have a script that I use to construct both the tables and stored procedures. For example I have a column of type varchar. varchar requires a size parameter, that size I also use as parameters in stored procedures and within those procedures.
is it possible to have thequivalentnt of a #define for its size, so I can easily adjust the size without the necessity of having to change ithroughht the whole of the script?
I am using MySql workbench.
EDIT
I have tried SET and DECLARE
I have a script - this is (abridged)
CREATE TABLE `locations`
(
`location` VARCHAR(25) NOT NULL
);
...
CREATE PROCEDURE AddLocation (IN location VARCHAR(25)
BEGIN
...
END$$
What I am trying to achieve is replace the values 25 in the script with a constant - similar to a #define at the top of the script that creates the table and stored procedures, so I am able to easily change the 25 to another number.
Anybody has found a solution to this problem?
The C Pre Processor (cpp) is historically associated with C (hence the name), but it really is a generic text processor that can be used (or abused) for something else.
Consider this file, named location.src (more on that later).
// C++ style comments works here
/* C style works also */
-- plain old SQL comments also work,
-- but you should avoid using '#' style of comments,
-- this will confuse the C pre-processor ...
#define LOCATION_LEN 25
/* Debug helper macro */
#include "debug.src"
DROP TABLE IF EXISTS test.locations;
CREATE TABLE test.locations
(
`location` VARCHAR(LOCATION_LEN) NOT NULL
);
DROP PROCEDURE IF EXISTS test.AddLocation;
delimiter $$
CREATE PROCEDURE test.AddLocation (IN location VARCHAR(LOCATION_LEN))
BEGIN
-- example of macro
ASSERT(length(location) > 0, "lost or something ?");
-- do something
select "Hi there.";
END
$$
delimiter ;
and file debug.src, which is included:
#ifdef HAVE_DEBUG
#define ASSERT(C, T) \
begin \
if (not (C)) then \
begin \
declare my_msg varchar(1000); \
set my_msg = concat("Assert failed, file:", __FILE__, \
", line: ", __LINE__, \
", condition ", #C, \
", text: ", T); \
signal sqlstate "HY000" set message_text = my_msg; \
end; \
end if; \
end
#else
#define ASSERT(C, T) begin end
#endif
When compiled with:
cpp -E location.src -o location.sql
you get the code you are looking for, with cpp expanding #define values.
When compiled with:
cpp -E -DHAVE_DEBUG location.src -o location.sql
you get the same, plus the ASSERT macro (posted as a bonus, to show what could be done).
Assuming a build with HAVE_DEBUG deployed in a testing environment (in 5.5 or later since SIGNAL is used), the result looks like this:
mysql> call AddLocation("Here");
+-----------+
| Hi there. |
+-----------+
| Hi there. |
+-----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> call AddLocation("");
ERROR 1644 (HY000): Assert failed, file:location.src, line: 24, condition length(location) > 0, text: lost or something ?
Note how the file name, line number, and condition points right at the place in the source code in location.src where the assert is raised, thanks again to the C pre processor.
Now, about the ".src" file extension:
you can use anything.
Having a different file extension helps with makefiles, etc, and prevents confusion.
EDIT: Originally posted as .xql, renamed to .src for clarity. Nothing related to xml queries here.
As with any tools, using cpp can lead to good things, and the use case for maintaining LOCATION_LEN in a portable way looks very reasonable.
It can also lead to bad things, with too many #include, nested #ifdef hell, macros, etc that at the end obfuscate the code, so your mileage may vary.
With this answer, you get the whole thing (#define, #include, #ifdef, __FILE__, __LINE__, #C, command line options to build), so I hope it should cover it all.
Have you tried SET?
here is an example :
SET #var_name = expr
more examples here :
http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
It sounds like you're looking for user defined data types. Unfortunately for us all mySQL doesn't yet support user defined data types like SQL Server, Oracle, and others do.
Here's a list of supported data types:
http://dev.mysql.com/doc/refman/5.0/en/data-types.html
For those that are interested:
I ended up writing a PHP script because:
a) The machine that can access the database does not belong to me and I cannot access the C
preprocessor
b) The other the two answers do not work.
c) Seemed the simplest solution
Here is the script for those who might find it useful. I am using it to define the tables column
widths and then use those same values in the stored procedures. This is due to the column
widths have not yet been fully decided for production.
I have also built in that you can define strings that last over a few lines. This has the advantage that I can obey the 80 column width (hence printing looks readable).
Here is the script
<?php
if (1==count($argv))
{
?>
Processing #defines from stdin and send to SQL server:
This script will remove
1. #define <name> <integer>
2. #define <name> '<string>'
3. #define <name> '<string>' \
'<continuation of string>'
and replace the occurances of name with the #define value as specified
<name> is upper case alpha numberics or underscores, not starting with a
digit.
The arguments of this script is passed to the mysql executable.
<?php
exit(1);
}
function replace(&$newValues, $a, $b, $c)
{
return $a . (array_key_exists($b, $newValues) ? $newValues[$b] : $b) . $c;
}
// The patterns to be used
$numberPattern='/^#define[ \t]+([A-Z_][A-Z0-9_]*)[ \t]+(0|([1-9][0-9]*))'.
'[ \t]*[\r\n]+$/';
$stringPattern= '/^#define[ \t]+([A-Z_][A-Z0-9_]*)[ \t]+\''.
'((\\\'|[^\'\r\n])*)\'[ \t]*(\\\\{0,1})[\n\r]+$/';
$continuationPattern='/^[ \t]*\'((\\\'|[^\'\r\n])*)\'[ \t]*'.
'(\\\\{0,1})[\n\r]+$/';
// String to be evaluated to replace define values with a new value
$evalStr='replace($newValues, \'\1\', \'\2\', \'\3\');';
array_splice($argv, 0, 1);
// Open up the process
$mysql=popen("mysql ".implode(' ', $argv), 'w');
$newValues=array(); // Stores the defines new values
// Variables to control the replacement process
$define=false;
$continuation=false;
$name='';
$value='';
while ($line=fgets(STDIN))
{
$matches=array();
// #define numbers
if (!$define &&
1 == preg_match($numberPattern, $line, $matches))
{
$define = true;
$continuation = false;
$name = $matches[1];
$value = $matches[2];
}
// #define strings
if (!$define &&
1 == preg_match($stringPattern,
$line, $matches))
{
$define = true;
$continuation = ('\\' == $matches[4]);
$name = $matches[1];
$value = $matches[2];
}
// For #define strings that continue over more than one line
if ($continuation &&
1 == preg_match($continuationPattern,
$line, $matches))
{
$value .= $matches[1];
$continuation = ('\\' == $matches[3]);
}
// Have a complete #define, add to the array
if ($define && !$continuation)
{
$define = $continuation = false;
$newValues[$name]=$value;
}
elseif (!$define)
{
// Do any replacements
$line = preg_replace('/(^| |\()([A-Z_][A-Z0-9_]*)(\)| |$)/e',
$evalStr, $line);
echo $line; // In case we need to have pure SQL.
// Send it to be processed.
fwrite($mysql, $line) or die("MySql has failed!");
}
}
pclose($mysql);
?>

Passing 2d array to function in Lua

It is possible to pass 2d array to a function as a paramter ?
I initialized an array like this :
tab={}
for i=1, 10 do
tab[i]={}
for z=1, 10 do
tab[i][z]= 0
end
end
and i have function like this :
function foo(data)
...
x = data[i][z] -- here i got error
...
end
The gave the error message attempt to index field '?' (a nil value)
All variables are declared and initialized.
Your code should work if it is initialized properly.
For example, the below code sample will output 3:
function foo(data)
local i, z = 1, 2
print(data[i][z])
end
local tab={}
for i=1, 10 do
tab[i]={}
for z=1, 10 do
tab[i][z]= i + z
end
end
foo(tab)
Maybe you can share the rest of your code? The following runs with no error:
tab={}
for i=1, 10 do
tab[i]={}
for z=1, 10 do
tab[i][z]= 0
end
end
function foo(data)
print(data[3][2])
end
foo(tab)
The gave the error message attempt to index field '?' (a nil value)
I got such errors while changing metatable of some variable.