removing debug code with google closure REST service? - google-closure-compiler

How do I remove debug code from javascript with the google closure REST service.
I know that I have to specify the debug variable to the JS compiler like this:
--define='DEBUG=false'
(with DEBUG being used in if conditions).
But how do I specify this to the REST service: http://closure-compiler.appspot.com/home
I tried this, but it doesn't work. That is: the code is optimized but it still contains the debug code :(
// ==ClosureCompiler==
// #output_file_name default.js
// #compilation_level ADVANCED_OPTIMIZATIONS
-- define='DEBUG=false'
// ==/ClosureCompiler==
/** #define {boolean} */
var DEBUG = true;
/**#constructor*/
function MyObject() {
this.test = 4;
if (DEBUG) {
this.toString = function () { return "test object"; };
}
}
window['MyObject'] = MyObject

The Closure REST service usually maps command line options to the lines between the comment block. Options are prefixed with "#" with the "=" sign stripped off. It, however, does not seem to work for #define (which should map to --define). I suspect that the REST code is confused with the extra "=" in DEBUG=false.
This should work:
#define DEBUG=false
or
#define 'DEBUG=false'
but doesn't.

The define parameter is currently not supported for the REST service.
Only these and these parameters are supported.

Related

Call method .NET from JavaScript

I have a method in .NET (GetDataStationParts), which I declare with 2 parameters, I want to call it from a JavaScript, and I use the InvokeMethodAsyn function in this way:
const { data } = require("jquery");
function GetParteScrap()
{
var idestacionjs = document.getElementById('getestacion');
var idmodelojs = document.getElementById('getmodelo');
var tablascrap = DotNet.InvokeMethodAsyn("YMMScrapSystem", "GetDataStationParts", idestacionjs, idmodelojs);
console.log(tablascrap);
}
To do it, I base it on an example on the web but I'm not sure where it gets the DotNet object to then invoke the method, the intention of my code is that after selecting parameters of 2 , go to the database and execute a SQL-level function, which will return a table, with the function GetDataStationParts, I try to give it the functionality to execute my method at the DB level as follows
[JSInvokable]
public async Task<IEnumerable<GetEstacionParte>>GetDataStationParts(int modelo, int estacion)
{
var resul = await _context.Set<GetEstacionParte>().FromSqlInterpolated($"SELECT * FROM dbo.GetEstacionParte({modelo},{estacion})").ToArrayAsync();
return resul;
}
The SQL level function works correctly, but when running the application at the console level in the browser, it throws the following error, where it indicates that the function is not defined
Where could the error be? Thank you for reading
require() is not a feature that is built into the browser. Javascript environment does not understand how to handle require(), In Node.js by Default this function is available.
I suspect you most probably missing some reference here. You can either download require.js from here & link with your application or use below script tag.
<script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>

Use QTest macros (QVERIFY, QCOMPARE, etc.) in function other than the test function

In general, the macros QVERIFY, QCOMPARE, etc. shall not be used outside a test function. The reason is, that in case of a failure, they interrupt the test with a return.
If I want to do tests in a function, I should do them by hand and return false if one of them fails. Then call the function with QVERIFY. But when I do this, I miss out the detailed output of the macros like the line where the error occurred.
So I'm looking for a way to use the macros outside of a test function. One solution is to create my own macro that interrupts the test when a macro call in the underlying function fails. The main problem here is to detect when a test has failed. Looking into Qt's code, in case of a fail the variable QTest::failed is set to true. But I don't have access to this variable.
Is there a way to find out if a QtTest macro has failed?
Yeah, Qt does not really offer anything here because the test will not really get interrupted within your own function. The control flow cannot be as easily disturbed. You would need to throw an exception and make sure it's correctly caught.
What I'm doing now is just returning a const char* (works when using a string literal). If the function actually returns something, std::variant can be used, e.g.:
std::variant<MyObject, const char*> createObject() {
// do some preparations
if(preparationsFail) {
return "Error occurred";
// all worked
// ...: create some myObject
return myObject;
}
void MyTest::testFunction() {
auto result = createObject();
if(const char** error = std::get_if<const char*>(&result)) {
QVERIFY2(false, *error); // we get pointer to value, so type is **
}
// else, work with myObject by std::get<MyObject>(result);
}
Not as concise as would be desired, but it works.
It can be made more beautiful by wrapping const char* and, depending on your style, by using std::visit etc. but that's up to you and your style.

Typescript reflection - required parameters & default values

In short: is there a way to know if a typescript parameter is required and/or has a default value?
Longer version:
Say I have the following file:
//Foo.ts
class Bar {
foo(required:string,defaultValue:number=0,optional?:boolean) {
...
}
}
I would like to know of each of the parameters:
the name
the type
is it required?
does it have a default value?
I have succesfully used method decorators with the TypeScript reflection API to get the types of the parameters, I've used this method to get their names, but so far I have not found a way to know if a variable is required and/or has a default value.
I know the typescript compiler itself can be used from within typescript. So I'm wondering if there is a way to use the parse tree of the compiler to see if a parameter is required and/or has a default value?
How would that work?
If you want to do this from scratch...
On a high level, one way of doing it is to:
Figure out how to get the SourceFile node using the compiler api of your file. That requires a bit of an explanation in itself.
From there, use the api's forEachChild function to loop over all the nodes in the file and find the node with a kind of SyntaxKind.ClassDeclaration and .name property with text Bar.
Then loop over all the children of the class by again using the api's forEachChild function and get the ones that has the kind SyntaxKind.MethodDeclaration and .name property with text foo.
To get the parameters, you will need to loop over the method node's parameters property.
Then for each parameter node, to get the name you can call .getText() on the .name property.
You can tell if the parameter is optional by doing:
const parameterDeclaration = parameterNode as ts.ParameterDeclaration;
const isOptional = parameterDeclaration.questionToken != null || parameterDeclaration.initializer != null || parameterDeclaration.dotDotDotToken != null;
Or you could use the TypeChecker's isOptionalParameter method.
To get its default expression, you will just have to check the initializer property:
propertyDeclaration.initializer;
To get the type use the TypeChecker's getTypeOfSymbolAtLocation method and pass in the symbol of the node... that gets a little bit complicated so I won't bother explaining it (think about how it's different with union types and such).
Don't do it from scratch...
I've created a wrapper around the TypeScript compiler api. Just use this code with ts-simple-ast (edit: Previously this talked about my old ts-type-info library, but ts-simple-ast is much better):
import { Project } from "ts-morph";
// read more about setup here:
// https://ts-morph.com/setup/adding-source-files
const project = new Project({ tsConfigFilePath: "tsconfig.json" });
const sourceFile = project.getSourceFileOrThrow("src/Foo.ts");
const method = sourceFile.getClassOrThrow("Bar").getInstanceMethodOrThrow("foo");
Once you have the method, it's very straightforward to get all the information you need from its parameters:
console.log(method.getName()); // foo
for (const param of method.getParameters()) {
console.log(param.getName());
console.log(param.getType().getText());
console.log(param.isOptional());
console.log(param.getInitializer() != null);
}

Message handling with ppapi_simple

As far as I understand one has two options to port a C program to Native Client:
Implement a number of initializing functions like PPP_InitializeModule and PPP_GetInterface.
Simply pass your main function to PPAPI_SIMPLE_REGISTER_MAIN.
So the question is how can I implement JS message handling (handle messages emitted by JS code in native code) in the second case?
Take a look at some of the examples in the SDK in examples/demo directory: earth, voronoi, flock, pi_generator, and life all use ppapi_simple.
Here's basically how it works:
When using ppapi_simple, all events (e.g. input events, messages from JavaScript) are added to an event queue. The following code is from the life example (though some of it is modified and untested):
PSEventSetFilter(PSE_ALL);
while (true) {
PSEvent* ps_event;
/* Process all waiting events without blocking */
while ((ps_event = PSEventTryAcquire()) != NULL) {
earth.HandleEvent(ps_event);
PSEventRelease(ps_event);
}
...
}
HandleEvent then determines what kind of event it is, and handles it in an application specific way:
void ProcessEvent(PSEvent* ps_event) {
...
if (ps_event->type == PSE_INSTANCE_HANDLEINPUT) {
...
} else if (ps_event->type == PSE_INSTANCE_HANDLEMESSAGE) {
// ps_event->as_var is a PP_Var with the value sent from JavaScript.
// See docs for it here: https://developers.google.com/native-client/dev/pepperc/struct_p_p___var
if (ps_event->as_var->type == PP_VARTYPE_STRING) {
const char* message;
uint32_t len;
message = PSInterfaceVar()->VarToUtf8(ps_event->as_var, &len);
// Do something with the message. Note that it is NOT null-terminated.
}
}
To send messages back to JavaScript, use the PostMessage function on the messaging interface:
PP_Var message;
message = PSInterfaceVar()->VarFromUtf8("Hello, World!", 13);
// Send a string message to JavaScript
PSInterfaceMessaging()->PostMessage(PSGetInstanceId(), message);
// Release the string resource
PSInterfaceVar()->Release(message);
You can send and receive other JavaScript types too: ints, floats, arrays, array buffers, and dictionaries. See also PPB_VarArray, PPB_VarArrayBuffer and PPB_VarDictionary interfaces.

Passing param to flex module via url

Im using a few modules repeatedly in a Flex app and varying the conditions by passing in params via the 'loaderInfo.url' var. This works fine for the first iteration of a given module but subsequent attempts will always see the same params as the first creation regardless of what is actually used.
Is there some way to reset this value when the module is created?
private var moduleInfo : IModuleInfo;
private function loadPageModule( pathString : String, pageParam : String ) : void
{
pathString = "modules/" + pathString + ".swf?param=" + pageParam;
moduleInfo = ModuleManager.getModule( pathString );
moduleInfo.addEventListener( ModuleEvent.READY, onPageModuleReady, false, 0, true);
moduleInfo.load( ApplicationDomain.currentDomain, null, null );
}
When I view the param in the 'CreationComplete' handler (eg 'trace( this.loaderInfo.url );') its the same every time (for a given module) regardless of what is actually passed in via the ?param=string. What am I doing wrong?
I'm little confused by your code. "moduleInfo" is a local variable in loadPageModule, meaning after the function executes it should be garbage collected. Typically adding a event listener would stop the object from being GC'ed but you specifically set the "weakListener" argument of addEventListener to true.
Can you set the weakListener argument of addEventListener to false and manually remove the listener in onPageModuleReady? Like below:
// change true to false on this line
moduleInfo.addEventListener( ModuleEvent.READY, onPageModuleReady, false, 0, false);
// tweak onPageModuleReady
private function onPageModuleReady(e:Event):void {
e.target.removeEventListener(ModuleEvent.READY, onPageModuleReady);
// that will allow the object to be GC'ed
...rest of your code
Test it again with that configuration and report back if things change.
Well I don't know why this is doing what its doing.. but.. an effective way to pass unique params to different instances of a module is to use the IModuleInfo.data param. The url method never worked properly (for me).

Resources