How can I call a routine automatically when the run ends in specman? - specman

Is there any way to specify that a function should be called when a test ends in Specman?
I'm looking for something similar to C's atexit().

haven't tried my self, but you should probably have a look at the finalize() or quit() methods which are defined for any_struct. You could try to extend it for sys.
extend sys {
finalize() is also {
// ...
};
};
Cheers,
Daniel

Related

Flutter & Dart: How to check/know which class has called a function?

I am trying to know which class has called a specific function. I've been looking through the docs for this, but without success. I already know how to get the name of a class, but that is something different of what I'm looking for. I found already something related for java but for dart I haven't. Maybe I'm missing something.
Let's say for example that I have a print function like so:
class A {
void printSomethingAndTellWhereYouDidIt() {
// Here I would also include the class where this function is
// being called. For instance:
print('you called the function at: ...');
//This dot-dot-dot is where maybe should go what I'm looking for.
}
}
class B {
A a = A();
void test() {
a.printSomethingAndTellWhereYouDidIt();
}
}
The output should be something like:
you called the function at: B
Please let me know if there are ways to achieve this. The idea behind is to then use this with a logger, for instance the logging package. Thank you in advance.
You can use StackTrace.current to obtain a stack trace at any time, which is the object that's printed when an exception occurs. This contains the line numbers of the chain of invocations leading up to the call, which should provide the information you need.
class A {
void printSomethingAndTellWhereYouDidIt() {
print(StackTrace.current);
}
}
class B {
A a = A();
void test() {
a.printSomethingAndTellWhereYouDidIt();
}
}
If you are doing this for debugging purposes, you can also set a breakpoint in printSomethingAndTellWhereYouDidIt to check where it was called from.

D: Delegates or callbacks?

I found conception of Delegates pretty hard for me. I really do not understand why I can't simply pass one function to another and need to wrap it to Delegate. I read in docs that there is some cases when I do not know it's name and Delegate is only way to call it.
But now I have trouble in understanding conception of callbacks. I tried to find more information, but I can't understand is it's simply call of other function or what is it.
Could you show examples of D callbacks and explain where they can be helpful?
import vibe.d;
shared static this()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, &handleRequest);
}
void handleRequest(HTTPServerRequest req,
HTTPServerResponse res)
{
if (req.path == "/")
res.writeBody("Hello, World!", "text/plain");
}
&handleRequest is it callback? How it's work and at what moment it's start?
So within memory a function is just a pile of bytes. Like an array, you can take a pointer to it. This is a function pointer. It has a type of RETT function(ARGST) in D. Where RETT is the return type and ARGST are the argument types. Of course attributes can be applied like any function declaration.
Now delegates are a function pointer with a context pointer. A context pointer can be anything from a single integer (argument), call frame (function inside of another) or lastly a class/struct.
A delegate is very similar to a function pointer type at RETT delegate(ARGST). They are not interchangeable, but you can turn a function pointer into a delegate pointer pretty easily.
The concept of a callback is to say, hey I know you will know about X so when that happens please tell me about X by calling this function/delegate.
To answer your question about &handleRequest, yes it is a callback.
You can pass functions to other functions to later be called.
void test(){}
void receiver(void function() fn){
// call it like a normal function with 'fn()'
// or pass it around, save it, or ignore it
}
// main
receiver(&test); // 'test' will be available as 'fn' in 'receiver'
You need to prepend the function name as argument with & to clarify you want to pass a function pointer. If you don't do that, it will instead call that function due to UFCS (calling without braces). It is not a delegate yet.
The function that receives your callable may do whatever it wants with it. A common example is in your question, a web service callback. First you tell the framework what should be done in case a request is received (by defining actions in a function and making that function available for the framework), and in your example enter a loop with listenHTTP which calls your code when it receives a request. If you want to read more on this topic: https://en.wikipedia.org/wiki/Event_(computing)#Event_handler
Delegates are function pointers with context information attached. Say you want to add handlers that act on other elements available in the current context. Like a button that turns an indicator red. Example:
class BuildGui {
Indicator indicator;
Button button;
this(){
... init
button.clickHandler({ // curly braces: implicit delegate in this case
indicator.color = "red"; // notice access of BuildGui member
});
button.clickHandler(&otherClickHandler); // methods of instances can be delegates too
}
void otherClickHandler(){
writeln("other click handler");
}
}
In this imaginary Button class all click handlers are saved to a list and called when it is clicked.
There were several questions in the OP. I am going to try to answer the following two:
Q: Could you show examples of D callbacks and explain where they can be helpful?
A: They are commonly used in all languages that support delegates (C# for an example) as event handlers. - You give a delegate to be called whenever an event is triggered. Languages that do not support delegates use either classes, or callback functions for this purpose. Example how to use callbacks in C++ using the FLTK 2.0 library: http://www.fltk.org/doc-2.0/html/group__example2.html. Delegates are perfect for this as they can directly access the context. When you use callbacks for this purpose you have to pass along all the objects you want to modify in the callback... Check the mentioned FLTK link as an example - there we have to pass a pointer to the fltk::Window object to the window_callback function in order to manipulate it. (The reason why FLTK does this is that back FLTK was born C++ did not have lambdas, otherwise they would use them instead of callbacks)
Example D use: http://dlang.org/phobos/std_signals.html
Q: Why I can't simply pass one function to another and need to wrap it to Delegate?
A: You do not have to wrap to delegates - it depends what you want to accomplish... Sometimes passing callbacks will just work for you. You can't access context in which you may want to call the callback, but delegates can. You can, however pass the context along (and that is what some C/C++ libraries do).
I think what you are asking is explained in the D language reference
Quote 1:
A function pointer can point to a static nested function
Quote 2:
A delegate can be set to a non-static nested function
Take a look at the last example in that section and notice how a delegate can be a method:
struct Foo
{
int a = 7;
int bar() { return a; }
}
int foo(int delegate() dg)
{
return dg() + 1;
}
void test()
{
int x = 27;
int abc() { return x; }
Foo f;
int i;
i = foo(&abc); // i is set to 28
i = foo(&f.bar); // i is set to 8
}
There are already excellent answers. I just want to try to make simple summary.
Simply: delegate allows you to use methods as callbacks.
In C, you do the same by explicitly passing the object (many times named context) as void* and cast it to (hopefully) right type:
void callback(void *context, ...) {
/* Do operations with context, which is usually a struct */
doSomething((struct DATA*)context, ...);
doSomethingElse((struct DATA*)context, ...);
}
In C++, you do the same when wanting to use method as callback. You make a function taking the object pointer explicitly as void*, cast it to (hopefully) right type, and call method:
void callback(void* object, ...) {
((MyObject*)object)->method(...);
}
Delegate makes this all implicitly.

Exposing boost::gregorian::date to Python using Boost.Python

I'd like to make boost::gregorian::date available to Python using Boost.Python. But how do I create a decent __str__ function when one is not available on the Boost date class? I'd like to write it like this:
BOOST_PYTHON_MODULE(mymodule)
{
class_<boost::gregorian::date>("Date")
.add_property("year", &boost::gregorian::date::year)
.add_property("month", &boost::gregorian::date::month)
.def("__str__", ???)
;
}
After some research I found the answer. You can supply static functions to .def as well. Just give it to_iso_extended_string and it gets the object as first argument.
BOOST_PYTHON_MODULE(mymodule)
{
class_<boost::gregorian::date>("Date")
.add_property("year", &boost::gregorian::date::year)
.add_property("month", &boost::gregorian::date::month)
.def("__str__", &to_iso_extended_string)
;
}

Objective-C passing methods as parameters

How do you pass one method as a parameter to another method? I'm doing this across classes.
Class A:
+ (void)theBigFunction:(?)func{
// run the func here
}
Class B:
- (void)littleBFunction {
NSLog(#"classB little function");
}
// somewhere else in the class
[ClassA theBigFunction:littleBFunction]
Class C:
- (void)littleCFunction {
NSLog(#"classC little function");
}
// somewhere else in the class
[ClassA theBigFunction:littleCFunction]
The type you are looking for is selector (SEL) and you get a method's selector like this:
SEL littleSelector = #selector(littleMethod);
If the method takes parameters, you just put : where they go, like this:
SEL littleSelector = #selector(littleMethodWithSomething:andSomethingElse:);
Also, methods are not really functions, they are used to send messages to specific class (when starting with +) or specific instance of it (when starting with -). Functions are C-type that doesn't really have a "target" like methods do.
Once you get a selector, you call that method on your target (be it class or instance) like this:
[target performSelector:someSelector];
A good example of this is UIControl's addTarget:action:forControlEvents: method you usually use when creating UIButton or some other control objects programmatically.
Another option is to look at blocks. It allows you to pass a block of code (a closure) around.
Here's a good write up on blocks:
http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1
Here's the apple docs:
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html
Objective C makes this operation relatively easy. Apple provides this documentation.
To directly address your question, you are not calling a function, but a selector. Here is some sample code:
Big Function:
+ (void)theBigFunction:(SEL)func fromObject:(id) object{
[object preformSelector:func]
}
Then for class B:
- (void)littleBFunction {
NSLog(#"classB little function");
}
// somewhere else in the class
[ClassA theBigFunction:#selector(littleBFunction) fromObject:self]
Then for class C:
- (void)littleCFunction {
NSLog(#"classC little function");
}
// somewhere else in the class
[ClassA theBigFunction:#selector(littleCFunction) fromObject:self]
EDIT: Fix selectors sent (remove the semicolon)
You can use Blocks for this purpose. http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html

How can I check if an object has a specific method?

I want to use a method of an object.
Like $myObject->helloWorld().
However there are a couple of methods so I loop through an array of method names and call the method like this:
my $methodName ="helloWorld";
$myObject->$methodNames;
This works quite nice but some objects don't have all methods.
How can I tell whether $myObject has a method called helloWorld or not?
You can use the UNIVERSAL::can method of all objects to determine what methods it supports:
if ($myObject->can($methodName)) {
$myObject->$methodName;
}
As Eric noted, you can usually use UNIVERSAL::can
It can be used either on an object as in your example ($obj->can($methodName)) or statically, on a class: (CLASS->can($methodName))
Please note that there are possible false negatives associated with using UNIVERSAL::can on objects/classes which have AUTOLOAD-ed methods - see the perldoc for details. So before using can() on an object/class, please be careful to verify that the class in question either does not use AUTOLOAD, or overrides can() to compensate, or uses forward declaration to compensate as described in can()'s perldoc - hat tip to brian d foy)
Also, please be careful to either ONLY call can() on actual objects, or encapsulate it in eval. It will die if called on a non-object (e.g. undef, scalar etc...)
The canonical way to use can is inside an eval block in case the thing that you have in your scalar variable isn't actually an object. You don't have to worry about that because you'll still get the right answer (a non-object or class can't respond to the method):
if( my $ref = eval { $obj->can( $method ) } ) {
$obj->$ref( #args );
}
The can has the added feature that it returns a code reference to the method. Sometimes that can be handy.
I used this method when checking database connections, passed into a function, such as
my $method = "ping";
if(defined ($local_dbh) && eval{ $local_dbh->can($method) } ) {
if ($local_dbh->ping) {
return $local_dbh;
}
}
else {
## do connection
...
}