\n problem when using javascript to exec "python -c " - javascript

function get_params(command_string,tpp){
var rt = "None"
// 如果存在->那么取出值并覆盖
if(command_string.search("->") != -1){
rt = /->(.*):/.exec(command_string)[1]
var rep = /\)(\s{0,1}->\s{0,1}.*):/.exec(command_string)[1];
command_string = command_string.replace(rep, "");
}
command_string = command_string.replace(/(^\s*)/g, "");
var func_name = /^def ([_\da-zA-Z]+)\(.*/.exec(command_string)[1]
var comon = `python -c "
import inspect
import json
from typing import *
from datetime import *
result = []
${command_string}
pass
for x in inspect.signature(${func_name}).parameters.values():
try:
result.append(dict(name=x.name, annotation=x.annotation.__name__ if x.annotation != inspect._empty else 'Undeclared', default= x.default if x.default != inspect._empty else 'Undeclared'))
except Exception:
result.append(dict(name=x.name, annotation=x.annotation._name if x.annotation != inspect._empty else 'Undeclared', default= x.default if x.default != inspect._empty else 'Undeclared'))
print(json.dumps(result))
"`
console.log(comon)
var message = execute(comon).toString();
return {
"params":GenarateParamDoc(JSON.parse(message), tpp),
"rt": rt
}
}
I try to use javascript to execute some python code by "python -c". it works in Linux,
but I don't know why failed in windows and mac,
I guess it caused by the difference between \n \r\n and \r.
so I want to ask how to fix this problem.
this project is in https://github.com/QUANTAXIS/QAHelper
you can clone it and run in vscode.

Related

fix doScript function error in InDesign script

I wrote a script for InDesign and used doScript to run a bat file. This script works on some systems and not on others.
The error is in the image.
I run as admin InDesign. But it gives another error.
How can I fix the error?
function batFile(str) {
var path = "~\\AppData\\Roaming\\test\\";
var filename = 'b1.bat';
var file1 = new File(path + filename);
file1.encoding = 'UTF-8';
file1.open('w');
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">%appdata%\\test\\t1.txt"
file1.write(txt);
file1.close();
var cmdcode = "CreateObject(\"WScript.Shell\").Run \"%appdata%\\test\\b1.bat\", 0, True";
app.doScript(cmdcode, ScriptLanguage.visualBasic, undefined, UndoModes.FAST_ENTIRE_SCRIPT);
var result = path + "t1.txt";
var arry = openFile2(result);
if (arry.length != 0) {
return arry;
} else {
return "null";
}
}
**
Update
I find the problem.
When a user name is composed of two parts, such as "your name" causes this problem. To address this issue, we need to put the address in two double quotations.
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">\"%appdata%\\test\\t1.txt"\"
**
Update 2
In Windows, when the user uses OneDrive, the AppData path also changes, which causes doScript not to run. for example:
c: \ users \ username \ appdata
Changes to:
c: \ users \ username \ onedrive \ appdata
This is a known bug reported in the UserVoice: https://indesign.uservoice.com/forums/601180-adobe-indesign-bugs/suggestions/41072476-type-library-is-not-automatically-created-by-cc202. A common trick to solve this is, run InDesign at least once as administrator on the client machine. This activates VBS support.
I can't tell what the problem with your script. But just in case, you can run bat file this way:
var bat_file = File("your_file.bat");
bat_file.execute();
Update
Based on your code I can offer the workaround: add & echo ok > %appdata%\\test\\ok.txt in your bat file and check if the file ok.txt exists before going further.
function batFile(str) {
var path = "~\\AppData\\Roaming\\test\\";
var filename = 'b1.bat';
var file1 = new File(path + filename);
file1.encoding = 'UTF-8';
file1.open('w');
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">%appdata%\\test\\t1.txt";
// add the file 'ok.txt' after the previous command is finished
txt += " & echo ok > %appdata%\\test\\ok.txt";
file1.write(txt);
file1.close();
// run the bat file
file1.execute();
// check if the file 'ok.txt' exists before going further
var ok = File(path + "ok.txt");
while (!ok.exists) $.sleep(100);
ok.remove();
// do stuff
var result = path + "t1.txt";
var arry = openFile2(result);
if (arry.length != 0) {
return arry;
} else {
return "null";
}
}

tau-prolog won't run a prolog code that I use CHR library in although it works on SWI-Prolog

I'm trying to use Tau Prolog to run a CHR code and it gives this error:
throw(error(existence_error(procedure, '/'(color, 1)), '/'(top_level, 0)))
although it works fine on SWI Prolog.
This is the Prolog code:
:- use_module(library(chr)).
:- chr_constraint(color/1).
color(X), color(Y) <=> mix(X,Y,Z) | color(Z).
color(brown) \ color(_) <=> true.
mix(red,blue,purple).
mix(blue,yellow,green).
mix(yellow,red,orange).
this is the query I run:
?- color(yellow), color(red).
This is the JS code I use to run Tau Prolog:
let res2 = "";
let callbackStr = true;
function postQuery(str) {
res2 += str + "\n";
if (str == false)
callbackStr = false;
}
router.post("/runQuery", async (req, res) => {
res2 = "";
let session = pl.create();
let call = postQuery;
let query = req.body.sentQuery;
session.consult(req.body.codeString);
session.query(query);
while (callbackStr == true) {
session.answer(call);
}
res.send(res2);
res2 = "";
callbackStr = true;
});
I think you have little chance of success with :-use_module(library(chr))., at least if nobody ported the code from other more mature Prologs to TAU-Prolog
But Falco Nogatz has a Javascript implementation of CHR that could help you.
As I see it, Prolog and CHR overlap (well, Prolog is larger), so using a different host language for your CHR rules could be easy - and convenient.

skip comma (,) in csv export

So, I have found several other SO questions with related answers and tried most of them but nothing seems to be working for me. May be because my case is much complicated than the previous ones.
Here is my csv file which has several special characters [, ' "]
ID,Name,Executable,Host,Timeout,Tags,Visible,
65,one test,SomePROXY=http://10.10.10.10 /abc/cde/efg/some.py -u tom -g 'some-abc-test' --passparams "one,two",example.com,1800,nothing,true,
My Expected excel format is:
ID: 65
Name: one test
Executable: SomePROXY=http://10.10.10.10 /abc/cde/efg/some.py -u tom -g 'some-abc-test' --passparams "one,two"
Host: example.com
Timeout: 1800
Tags: nothing
Visible: true
But due to comma in Executable field, "two" comes in new column.
I tried quoting everything under """ (as suggested in other answers) but that doesn't seems worked.
Can anyone please help me here.
Here is my code, which I am trying to use here (for ag-grid table )
$scope.export_data_csv = function(){
var LINE_SEPARATOR = '\r\n';
var COLUMN_SEPARATOR = ',';
var fileName = 'export.csv';
let csvString = '';
let columnsToExport = $scope.ag_grid_options.api.columnController.getAllDisplayedColumns();
// adding column headers.
columnsToExport.map((column) => {
csvString+= column.colDef.headerName;
csvString+= COLUMN_SEPARATOR;
});
csvString+= LINE_SEPARATOR;
// adding content of data currently loaded in the grid.
$scope.ag_grid_options.api.forEachNode( function(node) {
node.columnController.allDisplayedColumns.map((column) => {
let cellContent = node.valueService.getValue(column, node);
if(typeof(cellContent) == 'object'){
cellContent = cellContent.join("; ")
}
csvString+= (cellContent != null) ? cellContent : "";
csvString+= COLUMN_SEPARATOR;
});
csvString+= LINE_SEPARATOR;
});
// for Excel, we need \ufeff at the start
var blobObj = new Blob(["\ufeff", csvString], {
type: "text/csv;charset=utf-8;"
});
// Internet Explorer
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blobObj, fileName);
}
else {
// Chrome
var downloadLink = document.createElement("a");
downloadLink.href = window.URL.createObjectURL(blobObj);
downloadLink.download = fileName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
}
;
You have to declare the whole value of 'Excecutable' as string and escape the double quotes inside with an additional double quote.
ID,Name,Executable,Host,Timeout,Tags,Visible,
65,one test,"SomePROXY=http://10.10.10.10 /abc/cde/efg/some.py -u tom -g 'some-abc-test' --passparams ""one,two""",example.com,1800,nothing,true,

v8: How to include a Script inside FunctionTemplate

I'm doing this to have a MongoDB nodejs driver wrapper using nodejs add ons.
I want to create a wrapper to remove the asynchronous nature. Sadly, the said driver doesn't have 'sync' option.
I tried building the mongodb c driver and mongodb c++ driver but had no luck.
Here's my question:
How can I parse a stringed javascript function body to v8 function?
I have this code
//args[0] is from the parameter: const FunctionCallbackInfo<Value>& args
Local<ObjectTemplate> global_templ = ObjectTemplate::New();
global_templ->Set(String::NewFromUtf8(isolate, "db"), args[0]);
Local<Context> context = Context::New(isolate, NULL, global_templ);
string str1 = "";
str1 += "if(!(db.serverConfig.isConnected && db.serverConfig.isConnected())) ";
str1 += " return false;";
str1 += "else";
str1 += " return true;";
const char * str2 = str1.c_str();
context->Enter();
Local<String> source = String::NewFromUtf8(isolate, str2);
Local<Script> script = Script::Compile(source);
Local<Value> result = script->Run();
args.GetReturnValue().Set(result);
context->Exit();
this will produce an error : Illegal return statement
I concluded I have to put this function.
Local<FunctionTemplate> func = FunctionTemplate::New(isolate);
I don't know how to parse the function body into the template. :'(
PS: I'm a newb so please make the words newb friendly. lol. haha

TypeError: text.indexOf is not a function

I was playing around with javascript trying to make a word searcher for strings. However, when i run the code i get TypeError: text.indexOf is not a function. I don't think there is a syntax error, or maybe i am completly missing something.
var text = prompt("Paste Text Here").toUpperCase;
var word = prompt("What word would you like to search for?").toUpperCase;
var hits = [];
var n = text.indexOf(word);
hits.push(text[n]);
if (hits.length === 0) {
console.log("Your word could not be found.");
} else {
console.log("Your word was found " + hits.length + " times.");
}
var text = prompt("Paste Text Here").toUpperCase;
you should call function
var text = prompt("Paste Text Here").toUpperCase()

Categories