I exposed boost::gregorian::date with the following:
date_from_python_date{};
to_python_converter<date, date_to_python_date, true>{};
where date_to_python_date is a struct with the right convert function: it converts it to a python datetime.date.
Some c++ functions return date and calling them from python works.
At a later stage, I have a c++ class
class F {
/// ....
public:
boost::gregorian::date start;
};
which I register with:
class_<F, F*, bases<B>>("F")
.def_readwrite("start", &F::start, "FTD")
;
I do this after having python-registered date.
I then obtain an instance f of the F wrapper. But then, when I print
f.start
The error is:
No Python class registered for C++ class boost::gregorian::date
In short, the return policy used by def_readonly() and def_readwrite() will default to using return_internal_reference for user-defined class types (see make_getter()). This return policy will suppress the use of custom converters. To resolve this, replace def_readonly() and def_readwrite() with add_property(), providing a boost::python::return_value_policy with a type of boost::python::return_by_value.
Change:
namespace python = boost::python;
python::class_<F, F*, python::bases<B>>("F")
.def_readwrite("start", &F::start, "FTD")
;
to:
namespace python = boost::python;
python::class_<F, F*, python::bases<B>>("F")
.add_property("start",
python::make_getter(
&F::start, python::return_value_policy<python::return_by_value>()),
python::make_setter(
&F::start, python::return_value_policy<python::return_by_value>()),
"FTD")
;
Here is a complete example demonstrating this difference:
#include <boost/python.hpp>
/// Mocks...
// Mockup user defined type.
class spam {};
struct egg
{
spam spam;
};
// Mockup convert that converts spam into 'hello world' strings.
struct spam_converter
{
static PyObject* convert(const spam&)
{
namespace python = boost::python;
python::str result("hello world");
return python::incref(result.ptr());
}
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Enable spam to string converter.
python::to_python_converter<spam, spam_converter>();
// Expose egg.
python::class_<egg>("Egg")
// Expose egg::spam as spam1, access will fail to find converter.
.def_readonly("spam1", &egg::spam)
// Expose egg::spam as spam2, automatic conveter will be found.
.add_property("spam2",
python::make_getter(
&egg::spam, python::return_value_policy<python::return_by_value>()))
;
}
Interactive usage:
>>> import example
>>> egg = example.Egg()
>>> try:
... spam = egg.spam1 # expect to throw
... assert(False)
... except TypeError:
... assert(True)
...
>>> spam = egg.spam2
>>> assert(spam == "hello world")
Note that although the same egg::spam data-member instance was being exposed as Egg.spam1 and Egg.spam2, the manner in which the data-member was being exposed affected whether or not the automatic converter was found during dispatch.
Related
I'm trying to create a config file for my java app that can have lazy evaluation, for instance, contain an e-mail template with current date time. I use ConfigSlurper to parse the config file.
For some reason I can't find at https://groovy-lang.org/closures.html the description of the commonly used form (see build.gradle): prop1 { ... } prop2 { ... }. Am I looking at the wrong place?
My tests show that such closures are evaluated immediately and the example above can be rewritten as: prop1 = { ... }() prop2 = { ... }() (notice the parentheses, without them the evaluation is lazy).
I also don't understand why using dots in property without the equal sign cause MissingMethodException: No signature of method: groovy.util.ConfigObject.URL() if I use: server.URL { System.out.println('ccc'); 'asd' } in the example below.
It's disappointing that the choice is completely transparent for Groovy, but you have to check that a value is instance of Closure or GString when using java.
I used this article as the starting point https://blog.mrhaki.com/2009/08/grassroots-groovy-configuration-with.html
// We can group settings.
// The following settings are created:
// app.version, app.setting1, app.setting2, app.setting3, app.date, app.active
app {
System.out.println('aaa')
version = "1.0"
// We can write code to set up settings.
[1, 2, 3].each {
this."setting${it}" = it * 10
}
// We can use Java objects
date = new Date()
active = true
}
server.URL = "http://default"
// Environment specific settings override settings with the
// same name.
environments {
development {
server = { System.out.println('ccc'); 'asd' }
// server.URL = "${-> System.out.println('bbb');new Date()}http://localhost"
}
test {
server.URL = 'http://test:9080'
}
integrationtest {
server.URL = 'http://integrationtest/url'
}
production {
server.URL = 'http://prod/url'
}
}
My tests show that such closures are evaluated immediately and the
example above can be rewritten as: prop1 = { ... }()
Closures are not evaluated immediately. The parens above are causing the closure to be evaluated.
For some reason I can't find at https://groovy-lang.org/closures.html
the description of the commonly used form (see build.gradle): prop1 {
... } prop2 { ... }.
prop1 {} is invoking a method named prop1 and passing a closure as a parameter That code is equivalent to this:
def myClosure = {}
prop1(myClosure)
I also don't understand why using dots in property without the equal
sign cause MissingMethodException: No signature of method:
groovy.util.ConfigObject.URL()
Something like server.URL = 'http://test:9080' is assigning a value (http://test:9080) to a property (server.URL). If you remove the equal sign you are changing the expression fundamentally and then would be invoking a method named URL on an object named server and passing http://test:9080 as a parameter.
C expression:
#define EFX_REVERB_PRESET_GENERIC \
{ 1.0000f, 1.0000f, 0.3162f, 0.8913f, 1.0000f, 1.4900f, 0.8300f, 1.0000f, 0.0500f, 0.0070f, { 0.0000f, 0.0000f, 0.0000f }, 1.2589f, 0.0110f, { 0.0000f, 0.0000f, 0.0000f }, 0.2500f, 0.0000f, 0.2500f, 0.0000f, 0.9943f, 5000.0000f, 250.0000f, 0.0000f, 0x1 }
I want to define this expression in the .pxd file.
I have to pass this expression as parameters to some C functions. So I don't use it for Python.
Source: OpenAL-Soft: https://github.com/kcat/openal-soft/blob/master/include/AL/efx-presets.h#L37
It's worth realising that not everything has a direct translation from C to Cython. In this case EFX_REVERB_PRESET_GENERIC can't really be defined using a type because it isn't a type - it's just a collection of brackets and numbers. These brackets and numbers are only valid in a small number of places:
void other_func(WhateverTheStructIsCalled s);
void func() {
WhateverTheStructIsCalled s = EFX_REVERB_PRESET_GENERIC; // OK
s = EFX_REVERB_PRESET_GENERIC; // wrong - not an initialization
other_func(EFX_REVERB_PRESET_GENERIC); // also doesn't work
}
Therefore it doesn't really fit into Cython's model so you can't wrap it directly.
What I'd do is write a small C wrapper yourself. You can do this with Cython's "inline C code" function:
cdef extern from *:
"""
WhateverTheStructIsCalled get_EFX_REVERB_PRESET_GENERIC(void) {
WhateverTheStructIsCalled s = EFX_REVERB_PRESET_GENERIC;
return s;
}
"""
WhateverTheStructIsCalled get_EFX_REVERB_PRESET_GENERIC()
Then use get_EFX_REVERB_PRESET_GENERIC() to call this function and get the relevant initialized structure.
I use enums but can't find good way to check eqauling.
enum Turn {
A(value:Int);
B(value:Int);
}
class Test {
static function main() {
var turn = Turn.A(100);
//I want to Check turn is Turn.A(any value) without using 'switch'.
if (turn == Turn.A) ...
}
}
Is there any good and simple way to checking?
You can use the .match() function:
if (turn.match(Turn.A(_)))
I haven't tested this, but it might be faster using Type class:
if (Type.enumConstructor(turn) == "A") ...
Because it is unsafe ("A" could be a typo), I suggest to use ExprTools:
import haxe.macro.ExprTools.*;
if (Type.enumConstructor(turn) == toString(macro A)) ...
There is another way, but I don't think it is faster :
if (Type.enumIndex(turn) == Type.enumIndex(A(0))) ...
And you might get condition evaluated to true for different enums:
enum Color { Red; }
if (Type.enumIndex(turn) == Type.enumIndex(Red)) ... // true
I'm writing the library in typescript and have to keep some api
_(1).seconds()
the thing is that _ is a module, and in the previous implementation was like that
module.exports = valueFunction;
module.exports.seconds = seconds;
is it possible to implement the same in typescript ?
Here's one way to consider breaking it up, and have code-completion/intellisense work. There are a few options that would be closer to the original JavaScript implementation, however, getting code-completion to work can be a bit challenging.
The primary function _ is exported, and returns an exported class called Chained. It's in this class, where the functions that hang from the return value of _ would exist.
In the implementation file (sample.ts):
export class Chained {
constructor(private val: number) {
}
seconds(): number {
return this.val / 1000;
}
}
export function _(val: number): Chained {
return new Chained(val);
}
And then in use:
/// <reference path="sample.ts" />
import sample = require('./sample');
// create a simple alias for the exported _ function:
import _ = sample._;
var val = _(5000).seconds();
console.log(val);
The output would be 5 as seconds divides the original number by 1000.
If you needed the function to be available like:
_.seconds
as well as:
_().seconds()
Your options become more limited as while TypeScript supports extending a Function instance with properties, intellisense doesn't work:
// this won't work well:
export function _(val:number) : Chained {
return new Chained(val);
}
_["seconds"] = (val:number) : number => {
return val / 1000;
}
In my work, I have methods to return closures as inputs for markup builders. So, for testing purposes, can we make an expected closure and assert the expected one equal to the one returned by one method? I tried the following code, but the assert failed.
a = {
foo {
bar {
input( type : 'int', name : 'dum', 'hello world' )
}
}
}
b = {
foo {
bar {
input( type : 'int', name : 'dum', 'hello world' )
}
}
}
assert a == b
I do not think it will be feasible to assert the closures even after calling them.
//Since you have Markup elements in closure
//it would not even execute the below assertion.
//Would fail with error on foo()
assert a() != b()
Using ConfigSlurper will give the error about input() since the closure does not represent a config script (because it is a Markup)
One way you can assert the behavior is by asserting the payload (since you have mentioned MarkupBuilder). That can be easily done by using XmlUnit as below(mainly Diff).
#Grab('xmlunit:xmlunit:1.4')
import groovy.xml.MarkupBuilder
import org.custommonkey.xmlunit.*
//Stub out XML in test case
def expected = new StringWriter()
def mkp = new MarkupBuilder(expected)
mkp.foo {
bar {
input( type : 'int', name : 'dum', 'hello world' )
}
}
/**The below setup will not be required because the application will
* be returning an XML as below. Used here only to showcase the feature.
* <foo>
* <bar>
* <input type='float' name='dum'>Another hello world</input>
* </bar>
* </foo>
**/
def real = new StringWriter()
def mkp1 = new MarkupBuilder(real)
mkp1.foo {
bar {
input( type : 'float', name : 'dum', 'Another hello world' )
}
}
//Use XmlUnit API to compare xmls
def xmlDiff = new Diff(expected.toString(), real.toString())
assert !xmlDiff.identical()
assert !xmlDiff.similar()
Above looks like a functional test, but I would go with this test unless otherwise there is an appropriate unit test to assert two markup closures.