Is there any way to declare a function that can take both an int and a double as it's argument in MQL4? - function

I have these two functions:
void CheckOneConditionInt( int &SettingsEditValueInt );
void CheckOneConditionDbl( double &SettingsEditValueDbl );
They do the same stuff, but one is used with int values and another is used with double values. Is there any way to make it one function that can take int/double as an argument? For example:
void CheckOneCondition( void &SettingsEditValue );
PS: The example does not work of course.

Have you heard about method overloading? It is used in MQL4.5.
So, if you pass int value then Function( int value ) is called, if real - then Function( double value ) is called. If the algorithm applied to both types is same - maybe you can just skip Function( int value ), or add a wrapper inside the integer function, something like:
Function( int &value ){
double tmp = value/1.0;
Function( tmp );
value = ( int ) Normalize( tmp, 0 );
}

Yes and No.
While the New-MQL4.56789 extensions have introduced classes ( inside which there are means for multiple calling interfaces ( where one could being suited for double and another for int ), which could mean YES ),the MQL4 is in its initial design principles a compiled language with strong typing,which means NO.
Design decision rules
A sound and clear desing can answer the dilemma. There is no principal reason to have ambiguous, dual-typed calling interface in MQL4 problem domain.
Except for some theoretical experimentation, there is always a deterministic certainty, of what type the value to be passed to a function is, thus an amorphous dual-(multi)-typed calling interface is moreless an academical subject in MQL4 context of use.
Epilogue
If one indeed seeks for such an extremely artificial geekiness to achieve such non-deterministic agnosticism, let's first define a clear MQL4-domain use-case, for which such uncertaintiness of parameter type is both necessary and un-avoidable by other, available, means.

The problem is solved by using templates:
template<typename T>
void CheckOneCondition( T &SettingsEditValue );
I can then call it passing double or int parameter.

Related

What should I set the flags field of CUDA_BATCH_MEM_OP_NODE_PARAMS?

The CUDA graph API exposes a function call for adding a "batch memory operations" node to a graph:
CUresult cuGraphAddBatchMemOpNode (
CUgraphNode* phGraphNode,
CUgraph hGraph,
const CUgraphNode* dependencies,
size_t numDependencies,
const CUDA_BATCH_MEM_OP_NODE_PARAMS* nodeParams
);
but the documentation for this API call does not explain what the flags field of ... is used for, and what one should set the flags to. So what value should I be passing?
A related API function is cuStreamBatchMemOp
CUresult cuStreamBatchMemOp (
CUstream stream,
unsigned int count,
CUstreamBatchMemOpParams* paramArray,
unsigned int flags
);
it essentially takes the fields of CUDA_BATCH_MEM_OP_NODE_PARAMS as its separate parameters. Its documentation says that flags is "reserved for future expansion; must be 0".

Calling std::vector constructor when containing class manually allocated

I'm afraid to ask questions in case it turns out to be stupid... But I tried to search and don't see the same situation.
I'm retrofitting a std::vector into some existing legacy code that is mostly C style. Our next major release which isn't due for a year or two will jettison a lot of the legacy code. But for now, the way we work is, every project gets recompiled for the customer, depending on specs. Some projects are on Visual Studio 2008, some 2010, etc. My added std::vector code I'm working on has no visible problems when compiled with 2013, but, I get crashes within the STL code when running VS 2008 SP1.
The existing code has a struct, and a fixed size array in it:
#define MAX_REMOTE_CONN 75
typedef struct {
int rno;
int adrs;
bool integ_pending;
} RTUref;
typedef struct {
char device[64];
int port;
RTUref RTU[MAX_REMOTE_CONN];
// more stuff...
} Connect_Info;
So, my basic goal is to get rid of the hard coded size limit to the RTU array. So, I have revised it like this:
class{
public:
int rno;
int adrs;
bool integ_pending;
} RTUref;
typedef std::vector <RTUref> RTUlist;
typedef struct {
char device[64];
int port;
RTUlist RTU;
// more stuff...
} Connect_Info;
The Connect_Info structs are allocated using our own memory manager. Don't know much about it other than it is supposed to be more efficient than use malloc() and free(). I'm guessing that the constructor for RTU doesn't get called since the struct it is contained in data allocated by our own memory manager?
Nevertheless, the code where I size the array, put values into the array all at least seem to work okay. But, when I call .clear() I get a crash from within the STL. And as I said, only if I use 2008. If I use 2013, I don't get that crash.
Assuming pct is a pointer to an allocated Connect_Info structure, the the line:
pct->RTU.clear();
Generates a crash on VS 2008. I am able to resize and add elements to the array. And I even tried to add a check that I don't clear unless the size is greater than zero like so:
if (pct->RTU.size() > 0)
pct->RTU.clear();
And I still get the crash on the clear.
So, I made the educated guess that I need to call a constructor. But, I wasn't quite sure of how to do it. But, in the code where the Connect_Info struct is allocated, I tried to add contructor code like this:
pct->RTU = RTUlist();
It compiles. But, I then get a crash in the STL on that line.
I haven't yet tried to build a small contained test program, as I'm not even sure that I will be able to reproduce the problem without our memory manager. But, I will try if that is what I need to do. I thought maybe someone might see obviously what I'm doing wrong. I'm fairly novice to the STL.
A little background: there is a term in C++ called "POD Type" (or "Plain Old Data Type").
There are verbose rules, but basically things that may do special things on allocations, deallocations, or copies are not POD types. The original Connect_Info was a POD type since it didn't do special things at those times and didn't have any non-POD members.
However, since you added a std::vector (which is not a POD type because it has to do special things at allocation, deallocation, copy, etc (because it allocates memory)), Connect_Info is not a POD type.
POD types can be allocated safely with malloc and deallocated with free since they don't do special things. However, non-POD types cannot (except in exceedingly rare cases which you'll first see after several years of programming C++) be allocated like that.
C only has POD types, so malloc is perfectly acceptable. There are a few options you can do:
int main ( ... )
{
Connect_Info * info = new Connect_Info() ;
std::cout << info->port << std::endl ;
delete info ;
}
Or
Connect_Info * makeOne ()
{
void * ptr = malloc ( sizeof(Connect_Info) ) ;
if ( ! ptr ) return 0 ;
return new (ptr) Connect_Info () ; // "In-Place constructor"
}
void deleteOne ( Connect_Info * info )
{
if ( ! ptr ) return ;
info = info->~Connect_Info() ; // manually call its destructor with the weirdest syntax ever
// Note: I'm not 100% sure this call to 'free' is right because the in-place new can return a different pointer, but I don't know how to the get the original back
free ( static_cast<void*>(info) ) ;
}
int main ( ... )
{
Connect_Info * info = makeOne ()
std::cout << info->port << std::endl ;
deleteOne ( info ) ;
}
If you have boost available (or C++11, which you probably don't), this is a MUCH better option (and only uses header components of boost):
boost::shared_ptr<Connect_Info> makeOne ()
{
return boost::make_shared<Connect_Info> () ;
}
int main ( ... )
{
boost::shared_ptr<Connect_Info> info = makeOne ()
std::cout << info->port << std::endl ;
// nothing else: shared_ptr takes care of that for you
}
(If you have C++11, use std::shared_ptr and std::make_shared)

controlling program flow without if-else / switch-case statements

Let's say I have 1000 functions defined as follows
void func dummy1(int a);
void func dummy2(int a, int aa);
void func dummy3(int a, int aa, int aaa);
.
.
.
void func dummy1000(int a, int aa, int aaa, ...);
I want to write a function that takes an integer, n (n < 1000) and calls nth dummy function (in case of 10, dummy10) with exactly n arguments(arguments can be any integer, let's say 0) as required. I know this can be achieved by writing a switch case statement with 1000 cases which is not plausible.
In my opinion, this cannot be achieved without recompilation at run time so languages like java, c, c++ will never let such a thing happen.
Hopefully, there is a way to do this. If so I am curious.
Note: This is not something that I will ever use, I asked question just because of my curiosity.
In modern functional languages, you can make a list of functions which take a list as an argument. This will arguably solve your problem, but it is also arguably cheating, as it is not quite the statically-typed implementation your question seems to imply. However, it is pretty much what dynamic languages such as Python, Ruby, or Perl do when using "manual" argument handling...
Anyway, the following is in Haskell: it supplies the nth function (from its first argument fs) a list of n copies of the second argument (x), and returns the result. Of course, you will need to put together the list of functions somehow, but unlike a switch statement this list will be reusable as a first-class argument.
selectApplyFunction :: [ [Int] -> a ] -> Int -> Int -> a
selectApplyFunction fs x n = (fs !! (n-1)) (replicate n x)
dummy1 [a] = 5 * a
dummy2 [a, b] = (a + 3) * b
dummy3 [a, b, c] = (a*b*c) / (a*b + b*c + c*a)
...
myFunctionList = [ dummy1, dummy2, dummy3, ... ]
-- (myfunction n) provides n copies of the number 42 to the n'th function
myFunction = selectApplyFunction myFunctionList 42
-- call the 666'th function with 666 copies of 42
result = myFunction 666
Of course, you will get an exception if n is greater than the number of functions, or if the function can't handle the list it is given. Note, too, that it is poor Haskell style -- mainly because of the way it abuses lists to (abusively) solve your problem...
No, you are incorrect. Most modern languages support some form of Reflection that will allow you to call a function by name and pass params to it.
You can create an array of functions in most of modern languages.
In pseudo code,
var dummy = new Array();
dummy[1] = function(int a);
dummy[2] = function(int a, int aa);
...
var result = dummy[whateveryoucall](1,2,3,...,whateveryoucall);
In functional languages you could do something like this, in strongly typed ones, like Haskell, the functions must have the same type, though:
funs = [reverse, tail, init] -- 3 functions of type [a]->[a]
run fn arg = (funs !! fn) $ args -- applies function at index fn to args
In object oriented languages, you can use function objects and reflection together to achieve exactly what you want. The problem of the variable number of arguments is solved by passing appropriate POJOs (recalling C stucts) to the function object.
interface Functor<A,B> {
public B compute(A input);
}
class SumInput {
private int x, y;
// getters and setters
}
class Sum implements Functor<SumInput, Integer> {
#Override
public Integer compute(SumInput input) {
return input.getX() + input.getY();
}
}
Now imagine you have a large number of these "functors". You gather them in a configuration file (maybe an XML file with metadata about each functor, usage scenarios, instructions, etc...) and return the list to the user.
The user picks one of them. By using reflection, you can see what is the required input and the expected output. The user fills in the input, and by using reflection you instantiate the functor class (newInstance()), call the compute() function and get the output.
When you add a new functor, you just have to change the list of the functors in the config file.

tcllib Tcl_CreateObjTrace usage example

Does anyone have an example of how to use Tcl_CreateObjTrace? This is the procedure to add Tcl calls tracing to the C code using TclLib.
My main problem is this: I'm trying to develop a tracer for my Tcl code. However, I'd like to trace only my own procedures. The following code works:
static int
tcl_tracer( ClientData clientData,
Tcl_Interp* interp,
int level,
CONST char* command,
Tcl_Command commandToken,
int objc, Tcl_Obj *CONST objv[])
{
int param_length = 0;
CONST char *param_str = NULL;
int i;
/**
* The first three parameters represent the procedure
*/
if (objc < 2) {
printf("Invalid number of parameters for the tracer: %d\n", objc);
return TCL_OK;
}
param_str = Tcl_GetStringFromObj(objv[0], &param_length);
printf("%d:%s ", 0, param_str);
param_str = Tcl_GetStringFromObj(objv[1], &param_length);
printf("%d:%s ", 1, param_str);
param_str = Tcl_GetStringFromObj(objv[2], &param_length);
printf("%d:%s ", 2, param_str);
printf("\n");
return TCL_OK;
}
However, it traces all procedures. It traces 'puts', 'set', etc.
Is there any way to avoid that? There is a parameter to specify the level of tracing. But I don't know beforehand how many levels deep my code may run.
Much appreciated.
-Ilya.
As that page mentions, setting the flags parameter of the Tcl_CreateObjTrace call to TCL_ALLOW_INLINE_COMPILATION will disable the most intrusive level of tracing (in particular, many common core commands are bytecode compiled as normal with that flag set).
That said, it is substantially easier to hook into this mechanism from the Tcl level through trace add execution; setting an enter trace on each command you're interested in (sorry, you'll have to list them) should do the trick. (This works because the trace internals can turn off a lot of the cost in a way your code can't. This is fairly tricky, and one of the reasons I hate dealing with the trace command implementation.)

Lists in User Defined Types (SQL Server 2008)

I'm trying to define a new type and have not had much luck finding any information about using lists within them. Basically my new type will contain two lists, lets say x and y of type SqlSingle (the user defined type is written in C#) is this even possible?
If not how are you supposed to go about simulating a two lists of an arbitary length in an SQL Server 2008 column?
I'm possibly going about this the wrong way but it is the best approach I can think of at the moment. Any help is very much appreciated.
You can use a List<T> in a CLR UDT - although CLR types are structs, which should be immutable, so a ReadOnlyCollection<T> would be a better choice if you don't have a very compelling reason for the mutability. What you need to know in either case is that SQL won't know how to use the list itself; you can't simply expose the list type as a public IList<T> or IEnumerable<T> and be on your merry way, like you would be able to do in pure .NET.
Typically the way to get around this would be to expose a Count property and some methods to get at the individual list items.
Also, in this case, instead of maintaining two separate lists of SqlSingle instances, I would create an additional type to represent a single point, so you can manage it independently and pass it around in SQL if you need to:
[Serializable]
[SqlUserDefinedType(Format.Native)]
public struct MyPoint
{
private SqlSingle x;
private SqlSingle y;
public MyPoint()
{
}
public MyPoint(SqlSingle x, SqlSingle y) : this()
{
this.x = x;
this.y = y;
}
// You need this method because SQL can't use the ctors
[SqlFunction(Name = "CreateMyPoint")]
public static MyPoint Create(SqlSingle x, SqlSingle y)
{
return new MyPoint(x, y);
}
// Snip Parse method, Null property, etc.
}
The main type would look something like this:
[Serializable]
[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = true, MaxByteSize = ...)]
public struct MyUdt
{
// Make sure to initialize this in any constructors/builders
private IList<MyPoint> points;
[SqlMethod(OnNullCall = false, IsDeterministic = true, IsPrecise = true)]
public MyPoint GetPoint(int index)
{
if ((index >= 0) && (index < points.Count))
{
return points[index];
}
return MyPoint.Null;
}
public int Count
{
get { return points.Count; }
}
}
If you need SQL to be able to get a sequence of all the points, then you can add an enumerable method to the sequence type as well:
[SqlFunction(FillRowMethodName = "FillPointRow",
TableDefinition = "[X] real, [Y] real")]
public static IEnumerable GetPoints(MyUdt obj)
{
return obj.Points;
}
public static void FillPointRow(object obj, out SqlSingle x, out SqlSingle y)
{
MyPoint point = (MyPoint)obj;
x = point.X;
y = point.Y;
}
You might think that it's possible to use an IEnumerable<T> and/or use an instance method instead of a static one, but don't even bother trying, it doesn't work.
So the way you can use the resulting type in SQL Server is:
DECLARE #UDT MyUdt
SET #UDT = <whatever>
-- Will show the number of points
SELECT #UDT.Count
-- Will show the binary representation of the second point
SELECT #UDT.GetPoint(1) AS [Point]
-- Will show the X and Y values for the second point
SELECT #UDT.GetPoint(1).X AS [X], #UDT.GetPoint(1).Y AS [Y]
-- Will show all the points
SELECT * FROM dbo.GetPoints(#UDT)
Hope this helps get you on the right track. UDTs can get pretty complicated to manage when they're dealing with list/sequence data.
Also note that you'll obviously need to add serialization methods, builder methods, aggregate methods, and so on. It can be quite an ordeal; make sure that this is actually the direction you want to go in, because once you start adding UDT columns it can be very difficult to make changes if you realize that you made the wrong choice.
Lists as you describe are usually normalized - that is, stored in separate tables with one row per item - rather than trying to cram them into a single column. If you can share more info on what you are trying to accomplish, maybe we can offer more assistance.
Edit - suggested table structure:
-- route table--
route_id int (PK)
route_length int (or whatever)
route_info <other fields as needed>
-- waypoint table --
route_id int (PK)
sequence tinyint (PK)
lat decimal(9,6)
lon decimal(9,6)
waypoint_info <other fields as needed>