Why this Ruby + Qt code not working? - ruby

I have the following test code:
require 'Qt'
app = Qt::Application.new( ARGV )
wnd = Qt::Widget.new
layout = Qt::VBoxLayout.new( wnd )
splitter = Qt::Splitter.new( layout )
That fails in last line with strange error:
'initialize': unresolved constructor call Qt::Splitter (ArgumentError)
I have checked the Qt::Splitter API via rbqtapi, it has constructor that takes one Qt::Widget argument. What's wrong with that code?

layout is of type VBoxLayout, which is no base class of QWidget and thus cannot be used where an argument of type QWidget is expected. Guessing based on my experience with Qt in C++ and Python, I'd say you have to use:
splitter = Qt::Splitter.new(wnd)
layout.addWidget(splitter)

Related

Can asynchronous module definitions be used with abstract syntax trees on v8 engine to read third party dependencies? [duplicate]

I understand eval string-to-function is impossible to use on the browsers' application programming interfaces, but there must be another strategy to use third party dependencies without node.js on v8 engine, given Cloudflare does it in-house, unless they disable the exclusive method by necessity or otherwise on their edge servers for Workers. I imagine I could gather the AST of the commonjs module, as I was able to by rollup watch, but what might the actual steps be, by tooling? I mention AMD for it seems to rely on string-to-function (to-which I've notice Mozilla MDN says nothing much about it).
I have been exploring the require.js repositories, and they either use eval or AST
function DEFNODE(type, props, methods, base) {
if (arguments.length < 4) base = AST_Node;
if (!props) props = [];
else props = props.split(/\s+/);
var self_props = props;
if (base && base.PROPS) props = props.concat(base.PROPS);
var code = "return function AST_" + type + "(props){ if (props) { ";
for (var i = props.length; --i >= 0; ) {
code += "this." + props[i] + " = props." + props[i] + ";";
}
var proto = base && new base();
if ((proto && proto.initialize) || (methods && methods.initialize))
code += "this.initialize();";
code += "}}";
//constructor
var cnstor = new Function(code)();
if (proto) {
cnstor.prototype = proto;
cnstor.BASE = base;
}
if (base) base.SUBCLASSES.push(cnstor);
cnstor.prototype.CTOR = cnstor;
cnstor.PROPS = props || null;
cnstor.SELF_PROPS = self_props;
cnstor.SUBCLASSES = [];
if (type) {
cnstor.prototype.TYPE = cnstor.TYPE = type;
}
if (methods)
for (i in methods)
if (HOP(methods, i)) {
if (/^\$/.test(i)) {
cnstor[i.substr(1)] = methods[i];
} else {
cnstor.prototype[i] = methods[i];
}
}
//a function that returns an object with [name]:method
cnstor.DEFMETHOD = function (name, method) {
this.prototype[name] = method;
};
if (typeof exports !== "undefined") exports[`AST_${type}`] = cnstor;
return cnstor;
}
var AST_Token = DEFNODE(
"Token",
"type value line col pos endline endcol endpos nlb comments_before file raw",
{},
null
);
https://codesandbox.io/s/infallible-darwin-8jcl2k?file=/src/mastercard-backbank/uglify/index.js
https://www.youtube.com/watch?v=EF7UW9HxOe4
Is it possible to make a C++ addon just to add a default object for
node.js named exports or am I Y’ing up the wrong X
'.so' shared library for C++ dlopen/LoadLibrary (or #include?)
“I have to say that I'm amazed that there is code out there that loads one native addon from another native addon! Is it done by acquiring and then calling an instance of the require() function, or perhaps by using uv_dlopen() directly?”
N-API: An api for embedding Node in applications
"[there is no ]napi_env[ just yet]."
node-api: allow retrieval of add-on file name - Missing module in Init
Andreas Rossberg - is AST parsing, or initialize node.js abstraction for native c++, enough?
v8::String::NewFromUtf8(isolate, "Index from C++!");
Rising Stack - Node Source
"a macro implicit" parameter - bridge object between
C++ and JavaScript runtimes
extract a function's parameters and set the return value.
#include <nan.h>
int build () {
NAN_METHOD(Index) {
info.GetReturnValue().Set(
Nan::New("Index from C++!").ToLocalChecked()
);
}
}
// Module initialization logic
NAN_MODULE_INIT(Initialize) {
/*Export the `Index` function
(equivalent to `export function Index (...)` in JS)*/
NAN_EXPORT(target, Index);
}
New module "App" Initialize function from NAN_MODULE_INIT (an atomic?-macro)
"__napi_something doesn't exist."
"node-addon-API module for C++ code (N-API's C code's headers)"
NODE_MODULE(App, Initialize);
Sep 17, 2013, 4:42:17 AM to v8-u...#googlegroups.com "This comes up
frequently, but the answer remains the same: scrap the idea. ;)
Neither the V8 parser nor its AST are designed for external
interfacing. In particular (1) V8's AST does not necessarily reflect
JavaScript syntax 1-to-1, (2) we change it all the time, and (3) it
depends on various V8 internals. And since all these points are
important for V8, don't expect the situation to change.
/Andreas"
V8 c++: How to import module via code to script context (5/28/22, edit)
"The export keyword may only be used in a module interface unit.
The keyword is attached to a declaration of an entity, and causes that
declaration (and sometimes the definition) to become visible to module
importers[ - except for] the export keyword in the module-declaration, which is just a re-use of the keyword (and does not actually “export” ...entities)."
SyntheticModule::virtual
ScriptCompiler::CompileModule() - "Corresponds to the ParseModule abstract operation in the ECMAScript specification."
Local<Function> foo_func = ...;//external
Local<Module> module = Module::CreateSyntheticModule(
isolate, name,
{String::NewFromUtf8(isolate, "foo")},
[](Local<Context> context, Local<Module> module) {
module->SetSyntheticModuleExport(
String::NewFromUtf8(isolate, "foo"), foo_func
);
});
Context-Aware addons from node.js' commonjs modules
export module index;
export class Index {
public:
const char* app() {
return "done!";
}
};
import index;
import <iostream>;
int main() {
std::cout << Index().app() << '\n';
}
node-addon-api (new)
native abstractions (old)
"Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect NODE_MODULE_VERSION and get yourself into a macro-tangle[ macro = extern atomics?]."
Scope Isolate (v8::Isolate), variable Local (v8::Local)
typed_array_to_native.cc
"require is part of the Asynchronous Module Definition AMD API[, without "string-to-function" eval/new Function()],"
node.js makes objects, for it is written in C++.
"According to the algorithm, before finding
./node_modules/_/index.js, it tried looking for express in the
core Node.js modules. This didn’t exist, so it looked in node_modules,
and found a directory called _. (If there was a
./node_modules/_.js, it would load that directly.) It then
loaded ./node_modules/_/package.json, and looked for an exports
field, but this didn’t exist. It also looked for a main field, but
this didn’t exist either. It then fell back to index.js, which it
found. ...require() looks for node_modules in all of the parent directories of the caller."
But java?
I won't accept this answer until it works, but this looks promising:
https://developer.oracle.com/databases/nashorn-javascript-part1.html
If not to run a jar file or something, in the Worker:
https://github.com/nodyn/jvm-npm
require and build equivalent in maven, first, use "dist/index.js".
Specifically: [ScriptEngineManager][21]
https://stackoverflow.com/a/15787930/11711280
Actually: js.commonjs-require experimental
https://docs.oracle.com/en/graalvm/enterprise/21/docs/reference-manual/js/Modules/
Alternatively/favorably: commonjs builder in C (v8 and node.js)
https://www.reddit.com/r/java/comments/u7elf4/what_are_your_thoughts_on_java_isolates_on_graalvm/
Here I will explore v8/node.js src .h and .cc for this purpose
https://codesandbox.io/s/infallible-darwin-8jcl2k?file=/src/c.cpp
I'm curious why there is near machine-level C operability in Workers if not to use std::ifstream, and/or build-locally, without node.js require.

How can I subclass an ipython cluster controller and engine to add options?

I have the basic PBS Controller and EngineSet Launchers working with my PBS/torque cluster. But now I'd like to pass in additional options through the config file and/or the command line to be rendered in the batch_template file using the {} template formatter syntax.
As an example, I want to run:
ipcluster start -n 10 --pmem=10gb
And then have, in my template:
#PBS -l pmem={pmem}
I guess that I have to subclass the PBSControllerLauncher & PBSEngineSetLauncher classes? This is mentioned in the documentation, but I can't find a clear example of how to do it.
Simply inheriting from these classes and adding pmem = Unicode(...) as a class attribute doesn't make pmem available in the template's context when it calls write_batch_script.
I can access the config options and insert it into the context, as shown below. This code works, but is pretty awkward and doesn't seem like the right way to do it:
from IPython.parallel.apps.launcher import PBSControllerLauncher, PBSEngineSetLauncher, BatchClusterAppMixin, ipcontroller_cmd_argv, ipengine_cmd_argv
from IPython.utils.traitlets import (
Any, Integer, CFloat, List, Unicode, Dict, Instance, HasTraits, CRegExp
)
import pipes
class MyPBSLauncherExtension(object):
def update_context(self):
cfg = self.config
ctx = self.context
cls = type(self).__name__
for c in ('extra_pbs_directives', 'extra_modules'):
if cls in cfg:
if c in cfg[cls]:
ctx[c] = cfg[cls][c]
continue
if c in cfg:
ctx[c] = cfg[c]
else:
ctx[c] = getattr(self, c)
class MyPBSControllerLauncher(PBSControllerLauncher, MyPBSLauncherExtension):
extra_pbs_directives = Unicode(u'', config=True, help='')
extra_modules = Unicode(u'', config=True, help='')
def write_batch_script(self, n):
self.update_context()
super(MyPBSControllerLauncher, self).write_batch_script(n)
class MyPBSEngineSetLauncher(PBSEngineSetLauncher, MyPBSLauncherExtension):
extra_pbs_directives = Unicode(u'', config=True, help='')
extra_modules = Unicode(u'', config=True, help='')
def write_batch_script(self, n):
self.update_context()
super(MyPBSEngineSetLauncher, self).write_batch_script(n)
Would very much appreciate a simple example that adds an additional option to a launcher subclass.

IONotificationPortCreate function call generates compiler error

I am having an issue with the IONotificationCreatePort function in IOKit:
var NotificationPort = IONotificationPortCreate(MasterPort)
IONotificationPortSetDispatchQueue(NotificationPort, DispatchQueue)
gives the following compiler error when NotificationPort is used in the function call in the second line
'Unmanaged IONotificationPort' is not identical to
'IONotificationPort'
if I use the following code based on the information in the Using Swift with Cocoa and Objective-C document, it compiles but generates a runtime error
var NotificationPort = IONotificationPortCreate(MasterPort).takeRetainedValue()
IONotificationPortSetDispatchQueue(NotificationPort, DispatchQueue)
Thread 1: EXC_BAD_ACCESS(code=1, address=0xwhatever)
So I think I have the run time error figured out, the IONotificationPort object does not have takeRetainedValue method
The crux of the problem as I see it, is that the IONotificationPortCreate function creates an IONotificationPort object and returns the reference to it.
I have looked all over the place and there is lots of information about and ways to pass references into a function call from Swift but nowhere can I find how to deal with references as a return value.
Can Swift call an object by reference?
Or am I way off the mark here????
Here is the objective C code that I am trying to convert to swift:
_notificationPort = IONotificationPortCreate(masterPort);
IONotificationPortSetDispatchQueue(_notificationPort, _controllerQueue);
Here is the complete code snippet from my swift file:
//Get IOKit Master Port
var MasterPort: mach_port_t = 0
let BootstrapPort: mach_port_t = 0
var MasterPortReturnCode: kern_return_t = 0
MasterPortReturnCode = IOMasterPort(BootstrapPort, &MasterPort)
println("Master port returned as \(MasterPort) with return code of \(MasterPortReturnCode)")
//Set up notification port and send queue
let DispatchQueue = dispatch_queue_create("com.apparata.AVB_Browser", DISPATCH_QUEUE_SERIAL)
var NotificationPort = IONotificationPortCreate(MasterPort)
IONotificationPortSetDispatchQueue(NotificationPort, DispatchQueue)

TRttiMethod::Invoke use

I would like to know how to use the Invoke method of the TRttiMethod class in C++Builder 2010.
This is my code
Tpp *instance=new Tpp(this);
TValue *args;
TRttiContext * ctx=new TRttiContext();
TRttiType * t = ctx->GetType(FindClass(instance->ClassName()));
TRttiMethod *m=t->GetMethod("Show");
m->Invoke(instance,args,0);
Show has no arguments and it is __published. When I execute I get a EInvocationError with message 'Parameter count mismatch'.
Can someone demonstrate the use of Invoke? Both no arguments and with arguments in the called method.
Thanks
Josep
You get the error because you are telling Invoke() that you are passing in 1 method parameter (even though you really are not, but that is a separate bug in your code). Invoke() takes an OPENARRAY of TValue values as input. Despite its name, the Args_Size parameter is not the NUMBER of parameters being passed in, but rather is the INDEX of the last parameter in the array. So, to pass 0 method parameters to Show() via Invoke(), set the Args parameter to NULL and the Args_Size parameter to -1 instead of 0, ie:
Tpp *instance = new Tpp(this);
TRttiContext *ctx = new TRttiContext;
TRttiType *t = ctx->GetType(instance->ClassType());
TRttiMethod *m = t->GetMethod("Show");
m->Invoke(instance, NULL, -1);
delete ctx;
Now, once you fix that, you will notice Invoke() start to raise an EInsufficientRtti exception instead. That happens when Runtime Packages are enabled. Unfortunately, disabling Runtime Packages will cause TRttiContext::GetType() to raise an EAccessViolation in TRttiPool::GetPackageFor() because of a known linker bug under C++:
QC #76875, RAID #272782: InitContext.PackageTypeInfo shouldn't be 0 in a C++ module:
Which causes these bugs:
QC #76672, RAID #272419: Rtti.pas is unusable in a C++ application
QC #76877, RAID #272767: AV in TRttiContext::GetType() when Runtime Packages are disabled
So you are in a catch-22 situation. The new RTTI system is not ready for production work in C++ yet. You will have to use Delphi instead for the time being.

Jython, ImageInfo

I trying to use ImageInfo and Jython to get information from a image on my harddrive.
I have imported the module fine but keep getting this error:
TypeError: setInput(): expected 2 args; got 1
And this is the code I am trying to use:
filename = "C:\\image.jpg"
img = ImageInfo.setInput(filename)
Could anyone point out what I am doing wrong.
Cheers
Eef
The missing argument Jython complains about is the ImageInfo object itself, which doesn't exist yet. You must construct it first. So:
filename = "C:\\image.jpg"
ii = ImageInfo()
img = ii.setInput(filename)
or
filename = "C:\\image.jpg"
img = ImageInfo().setInput(filename)
may work also.

Resources