I am totally new to this, i am learning this javascript. I am building an app/bot but am stuck at this. I didnt not write this code just found it on the web. So when the command start to execute i am getting this "catch" error but dont know what is problem. Most of the songs it wont show but accesing link in browser works fine: Here is the part of the code that gives error.
if (quizState) {
//Load current song stats
console.log(newMedia.author + " " + newMedia.duration);
var XMLsource = 'http://musicbrainz.org/ws/2/artist/?query=artist:' + newMedia.author.replace(/ /g, "%20") + '&limit=1';
simpleAJAXLib = {
init: function() {
this.fetchJSON(XMLsource);
},
fetchJSON: function(url) {
var root = 'https://query.yahooapis.com/v1/public/yql?q=';
var yql = 'select * from xml where url="' + url + '"';
var proxy_url = root + encodeURIComponent(yql) + '&format=json&diagnostics=false&callback=simpleAJAXLib.display';
document.getElementsByTagName('body')[0].appendChild(this.jsTag(proxy_url));
},
jsTag: function(url) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
return script;
},
display: function(results) {
try {
quizCountry = results.query.results.metadata["artist-list"].artist.area.name;
quizYear = results.query.results.metadata["artist-list"].artist["life-span"].begin.match(/\d{4}/);
quizBand = results.query.results.metadata["artist-list"].artist.name;
if (quizCountry != "" && quizYear != "") {
console.log(quizCountry + " " + quizYear);
API.sendChat("U kojoj godini je/su " + quizBand + " osnovan/i?");
}
} catch (e) {
console.log("Error: " + e.description);
API.sendChat("Žao nam je, čini se da musicbrainz ne prepoznaje ovaj bend ili umjetnika. Nastavit ćemo za vrijeme sljedeće pjesme.");
console.log("country or year not known");
}
}
}
simpleAJAXLib.init();
}
If the search on http://musicbrainz.org/ws/2/artist/? returns more than one artist, the object returns an array in
results.query.results.metadata["artist-list"].artist
So, to access the data, it would be
quizCountry = results.query.results.metadata["artist-list"].artist[0].area.name;
quizYear = results.query.results.metadata["artist-list"].artist[0]["life-span"].begin.match(/\d{4}/);
quizBand = results.query.results.metadata["artist-list"].artist[0].name;
So, you'll need to check if
results.query.results.metadata["artist-list"].count > 1
and change your code appropriately
e.g.
if(results.query.results.metadata["artist-list"].count > 1) {
quizCountry = results.query.results.metadata["artist-list"].artist[0].area.name;
quizYear = results.query.results.metadata["artist-list"].artist[0]["life-span"].begin.match(/\d{4}/);
quizBand = results.query.results.metadata["artist-list"].artist[0].name;
} else {
quizCountry = results.query.results.metadata["artist-list"].artist.area.name;
quizYear = results.query.results.metadata["artist-list"].artist["life-span"].begin.match(/\d{4}/);
quizBand = results.query.results.metadata["artist-list"].artist.name;
}
Although, you may want to change your logic totally if you get more than one artist in the response - but the above should fix your errors
Related
I was been trying to switch IDEs.
What if I will want to load MISRA check result file to Visual Studio.
Is there any direct or simpler way?
Made indirect workaround:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".");
var cStat = rootPath.files;
for(var objEnum = new Enumerator(cStat); !objEnum.atEnd(); objEnum.moveNext()) {
var strFileName = objEnum.item();
if (strFileName.ShortName.length - strFileName.ShortName.toUpperCase().indexOf(".TXT") != 4) continue;
//WScript.Echo(strFileName);
break;
}
var ts = strFileName.OpenAsTextStream(1);
while(!ts.AtEndOfStream) {
var textLine = ts.ReadLine();
textLine = textLine.split('\t'); // IAR MISRA line: Description Rule Severity File:Line
if (textLine[3])
{
var res = textLine[3].replace(/(.+):(\d+)/g, "$1($2)");
if (textLine[2] == "Low")
{
res += ": warning " + textLine[1] + ": " + textLine[0];
}
else
{
res += ": error " + textLine[1] + ": " + textLine[0] + ' ' + textLine[2];
}
WScript.Echo(res);
}
}
ts.Close();
Using fake NMAKE project with build command like cscript /NoLogo PrintLog.js.
Now I can open files reported by MISRA in VS by copying export txt file to this project and running build.
Similar older IAR warning(s) filter used as pipe by command:
...\iarbuild "project.ewp" ReleaseCfg | cscript /NoLogo IARfilterPipe.js.
var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".") + '\\';
var x = oldBad(), skip = {};
for (i in x) skip[x[i]] = 1;
var stat = [0, 0], all = [], newWarnings = [];
do {
var line = WScript.StdIn.ReadLine();
if (line.indexOf('[') > 0) // possible warning line
{
all.push(line);
line = line.replace(rootPath, "");
var fit = 0;
if (line.indexOf("Remark[") > -1)
{
fit++;
stat[0]++;
line = line
.replace(/\d+>\s+/g, "")
.replace(/Remark\[(\S+)\]:/g, "Warning $1:");
}
else if (line.indexOf("Error[") > -1)
{
fit++;
stat[1]++;
line = line
.replace(/\d+>\s+/g, "")
.replace(/Error\[(\S+)\]:/g, "Error $1:");
}
if (skip[line] != 1 && fit)
{
newWarnings.push(line);
WScript.Echo('!' + line);
var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
} else {
WScript.Echo('_' + line);
}
}
else {
var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
if (m == null) // no name.ext
{
WScript.Echo(line);
}
else if (m.length == 1) // single filename
{
all.push(line);
}
}
} while (!WScript.StdIn.AtEndOfStream);
if (all.length)
{
all = all.sort();
writeFile("buildFiles.txt", all.join('\n'));
}
if (newWarnings.length)
{
writeFile("newWarnings.txt", newWarnings.join('\n'));
WScript.Echo("========== New warnings: ==========");
}
for(var l in newWarnings)
{
WScript.Echo(newWarnings[l]);
}
if (stat[0] + stat[1])
{
WScript.Echo("========== Build Result - Warnings " + stat[0] + " Errors " + stat[1] + " ==========");
}
WScript.Quit(0); // (do not work from file after Echo => -1)
function writeFile(filename, content)
{
var TextStream = fso.CreateTextFile(filename);
TextStream.Write(content);
TextStream.Close()
}
function oldBad()
{
return [
'somefile.cpp(42) : Warning Pe340: value copied to temporary, reference to temporary used', ...
];
}
I am having an issue getting the javascript script for the executeScript nifi process to work and would appreciate help with this. The goal is to pass a flowfile which will contain a json object. I need to parse this json without knowing the content/fields prior and pass this along to write it out to the flowfile that is being passed out to the next process that is MergeContent and counts the number flowfiles.
Tried testing the script and got the following error:
nifi.script.ExecuteScript - ExecuteScript[id=bd6842e9-e3a4-4d88-a59d-
7da1d74d109b] ExecuteScript[id=bd6842e9-e3a4-4d88-a59d-7da1d74d109b]
failed to process due to
org.apache.nifi.processor.exception.ProcessException:
javax.script.ScriptException: <eval>:21:17 Expected : but found value
let value = json[key];
^ in <eval> at line number 21 at column number 17; rolling
back session: org.apache.nifi.processor.exception.ProcessException:
javax.script.ScriptException: <eval>:21:17 Expected : but found value
I am not very familiar with javascript so would appreciate the help.
flowFile = session.get();
if (flowFile != null) {
var StreamCallback =
Java.type("org.apache.nifi.processor.io.StreamCallback");
var IOUtils = Java.type("org.apache.commons.io.IOUtils");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
var transformed_message = {};
var error = false;
var line = "ops_testQueue";
flowFile = session.write(flowFile, new StreamCallback(function
(inputStream, outputStream) {
var content = IOUtils.toString(inputStream,
StandardCharsets.UTF_8); // message or content
var message_content = {};
try {
message_content = JSON.parse(content);
if(Array.isArray(message_content)){
}
Object.keys(message_content).forEach((key) => {
var value = json[key];
result.push(key + '=' + value);
var jkey = "," + "\"" + key + "\"" + '=' + value
});
line = line + jkey +
" value=" + "1"
+ " " + Date.now() * 1000000;
// Write output content
if (transformed_message) {
outputStream.write(line.getBytes(StandardCharsets.UTF_8));
}
} catch (e) {
error = true;
outputStream.write(content.getBytes(StandardCharsets.UTF_8));
}
}));
if (transformed_message.post_state) {
flowFile = session.putAttribute(flowFile, "type",
transformed_message.type);
}
if (error) {
session.transfer(flowFile, REL_FAILURE)
} else {
session.transfer(flowFile, REL_SUCCESS)
}
}
EDIT:
input to executeScript:
{"pID":"1029409411108724738",
"contentType":"text",
"published":"2018-08-14 16:48:23Z",
"crawled":"2018-08-14 12:48:33-04:00",
"ID":"765"}
output from executeScript:
ops_testQueue,"ID"=765 value=1 1534265314969999870
Am I missing something?
I saw a couple of things here:
I don't know if Nashorn (Java's JS Engine) supports the full lambda
syntax, I was able to get it to work by making the lambda a function
(see script below).
You refer to a json variable to get the value from a key, but I think you want message_content.
result is not defined, so you get an error when you push to it.
Here's an edited version of your script that I got to work the way I think you want it (but please correct me if I'm wrong):
flowFile = session.get();
if (flowFile != null) {
var StreamCallback =
Java.type("org.apache.nifi.processor.io.StreamCallback");
var IOUtils = Java.type("org.apache.commons.io.IOUtils");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
var transformed_message = {};
var error = false;
var line = "ops_testQueue";
flowFile = session.write(flowFile, new StreamCallback(function
(inputStream, outputStream) {
var content = IOUtils.toString(inputStream,
StandardCharsets.UTF_8); // message or content
var message_content = {};
try {
message_content = JSON.parse(content);
if(Array.isArray(message_content)){
}
var jkey = "";
Object.keys(message_content).forEach(function(key) {
var value = message_content[key];
//result.push(key + '=' + value);
jkey = "," + "\"" + key + "\"" + '=' + value
});
line = line + jkey +
" value=" + "1"
+ " " + Date.now() * 1000000;
// Write output content
if (transformed_message) {
outputStream.write(line.getBytes(StandardCharsets.UTF_8));
}
} catch (e) {
error = true;
log.error(e);
outputStream.write(content.getBytes(StandardCharsets.UTF_8));
}
}));
if (transformed_message.post_state) {
flowFile = session.putAttribute(flowFile, "type",
transformed_message.type);
}
if (error) {
session.transfer(flowFile, REL_FAILURE)
} else {
session.transfer(flowFile, REL_SUCCESS)
}
}
I am trying to open the serial port 2 on my beagle bone, using the following code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
The complete code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
b.pinMode("P9_17", b.OUTPUT);
var countTry =2;
var i = 0; // to loop over the array
var waiting_interval = 3000; // waiting for every slave to reply
var deli;
var slaves = ["S1", "S2" , "S3", "S4", "S5", "S6"];
var counter=[0 , 0 , 0 , 0 ,0 ,0];
var slave_exists = false;
serialPort.on('open',function onSerialOpen(){
console.log("opened");
serialPort.on('data', function listenToSlaves(data){
i--;
if(data.search("END" + slaves[i]) ==0){
console.log("ENDED");
slave_exists = true;
counter[i]=0;
}
else{
// if(data!="END" + slaves[i]){
if(data.search("END" + slaves[i])!==0){
deli = data.indexOf(":");
var parameter = data.substring(0, deli);
var value = data.substring(deli +1);
console.log("parameter is: " + parameter + " - Value is: " + value);
}
}
if(slave_exists){
counter[i] =0;
}
i++;
});
writeToSlaves();
});
function writeToSlaves(){
//If the previous slave (the slave before the one I am sending to
//in the next step doesnt exist, add the counter or consideer
//it not existing)
if(!slave_exists){
counter[i-1]+=1;
if(counter[i-1]>=countTry){
console.log("--------counter[" + i + "]: " + counter[i]);
// in case that the slave returned no data after trying
//to send him several times
console.log(slaves[i-1] + " doesn't exist");
}
}
//sending to the following slave
b.digitalWrite("P9_17", b.HIGH);
serialPort.write(slaves[i], function(){ slave_exists = false;});
b.digitalWrite("P9_17", b.LOW);
console.log("I wrote to slave: " + i);
if(i<slaves.length - 1) i++;
else i=0;
setTimeout(writeToSlaves, waiting_interval);
}
but I am always facing this error:events.js:72
throw er; // Unhandled 'error' event
^
Error: Cannot open /dev/ttyO2
I am running another file first (the code down), the I try to rerun the previous code, and it runs perfect. I need to do that whenever I want to run the first code!
The code that runs from the first time is here:
( I tried the following code alone, it writes to the serial port but doesnt recieve, no event at recieption):
var b = require('bonescript');
var rxport = '/dev/ttyO2';
var txport = '/dev/ttyO2';
var options = { baudrate: 115200, parity: 'even', parser: b.serialParsers.readline('\n') };
var teststring = "This is the string I'm sending out as a test";
b.serialOpen(rxport, options, onRxSerial);
function onRxSerial(x) {
console.log('rx.eventrx= ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
//readReapeatedly();
b.serialOpen(txport, options, onTxSerial);
}
if(x.event == 'data') {
console.log("I am receiving on rxport");
console.log('rx (' + x.data.length +
') = ' + x.data.toString('ascii'));
}
}
function onTxSerial(x) {
console.log('tx.event = ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
writeRepeatedly();
}
if(x.event == 'data') {
// console.log('tx (' + x.data.length +
// ') = ' + x.data.toString('ascii'));
console.log(x.data);
}
}
function printJSON(x) {
console.log(JSON.stringify(x));
}
function writeRepeatedly() {
console.log("write to serial");
b.serialWrite(txport, teststring, onSerialWrite);
console.log("I have sent data");
}
function onSerialWrite(x) {
console.log("Iam in the onSerialWrite function");
if(x.err) console.log('onSerialWrite err = ' + x.err);
if(x.event == 'callback') {setTimeout(writeRepeatedly, 5000);
console.log("HERE");
}
}
The problem was solved.
In /boot/uboot/uEnv.txt, Update the line:"#cape_enable=capemgr.enable_partno= " to be:
"cape_enable=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5 "
or add the last line to the mentioned file. In some cases, you need to try this line instead of the mentioned:
"optargs=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5" (this is my case - but it disabled the HDMI interface of my BBB).
You can specify the UART you want to enable.
A helpful webpage is here.
I made a function to add <a> tag in chat text and it worked fine, but it seems the variables of the function are shared between different instances of the function called from different chat rooms. I thought function variable were local, can anyone explain why I'm encountering this problem? Well I found out the code was wrong and a <p> tag the ajax function was adding to the string was interfering with this function. i fixed it by adding a space before the conflicting <p> tag and now it works fine...updated the code with english variable names too :)
function ajoutertagdelien(dataChat)
{
if (dataChat)
{
}
else
{
dataChat = " ";
}
var chatsendvar = dataChat;
var linkLocation, chatStringLeftPiece, chatfinal = "", chatStringRightPiece, lienfin, LinkAlone, LinktagString, LinkPiece;
var linkTagA = new Array();
var variablelocation = new Array();
var variablechatsend = new Array();
var increment=0;
var earlierLinkLength = 0;
linkLocation = chatsendvar.indexOf("www.");
while (linkLocation != -1) {
increment++;//
if (linkLocation != -1)
{
chatStringLeftPiece = chatsendvar.substring(0,linkLocation);
LinkPiece = chatsendvar.slice(linkLocation,chatsendvar.length);
lienfin = LinkPiece.indexOf(" ");
LinkAlone = LinkPiece.substring(0,lienfin);
chatStringRightPiece = chatsendvar.substring(((lienfin + linkLocation)),chatsendvar.length) ;
console.log( chatStringLeftPiece + " droit et gauche " + chatStringRightPiece + " number of theloop in the while=" + increment);
LinktagString = "<a target='_blank' href='http://"+ LinkAlone+"'>"+LinkAlone+"</a>";
chatsendvar = chatStringLeftPiece + " " + chatStringRightPiece;
linkTagA.push(LinktagString);
variablelocation.push(chatStringLeftPiece.length + earlierLinkLength);
earlierLinkLength = earlierLinkLength + LinktagString.length +1;
}
linkLocation = chatsendvar.indexOf("www.");
}
for (var x = 0, j = linkTagA.length; x<j; x++) {
chatsendvar = chatsendvar.split('');
chatsendvar.splice((variablelocation[x]),1," "+linkTagA[x]+" ");
chatsendvar = chatsendvar.join('');
};
return chatsendvar;
}
All this code to detect links in a text?
I know that's not what you asked, but this small function can do this. It can detect links beginning with www. or http:// and even handles url parameters, like ?a=1&b=2. Here is a demo fiddle.
The regex could be modified to handle https:// or url encoding for example, but you get my point.
function makeLinks(text) {
return text.replace(/(?:http:\/\/|(www\.))([\w\d.\/\?&=]+)/gi, '<a target="_blank" href="http://$1$2">$1$2</a>');
}
Ok, feeling stupid here, but wondering what the problem is here exactly.
Although the function works as it should, I get this JS Error in Opera. Not sure about other browsers...
Uncaught exception: TypeError: Cannot
convert
'document.getElementById("shoutbox_area"
+ moduleId)' to object
oElement = document.getElementById("shoutbox_area"
+ moduleId).childNodes;
Here is the relevant code:
function appendShout(XMLDoc)
{
var shoutData = XMLDoc.getElementsByTagName("item");
var oElement = [];
if (shoutData.length > 0)
{
var moduleId = shoutData[0].getAttribute("moduleid");
if (shoutData[shoutData.length - 1].getAttribute("lastshout") != "undefined")
{
for (var i = 0; i < shoutData.length; i++)
if (shoutData[i].firstChild.nodeValue != 0)
document.getElementById("shoutbox_area" + moduleId).innerHTML += shoutData[i].firstChild.nodeValue;
oElement = document.getElementById("shoutbox_area" + moduleId).childNodes;
var i = oElement.length;
while (i--)
{
if (i % 2 == 0)
oElement[i].className = "windowbg2";
else
oElement[i].className = "windowbg";
}
oElement[oElement.length - 2].style.borderBottom = "1px black dashed";
}
}
}
Can someone please help me to understand why it is giving me an error here:
oElement = document.getElementById("shoutbox_area" + moduleId).childNodes;
Can I not assign an array to the childNodes?
EDIT:
This JS Error occurs when I try and delete a shout. The JS function for deleting a shout is this:
function removeShout(shout, moduleID)
{
var shoutContainer = shout.parentNode.parentNode;
var send_data = "id_shout=" + shout.id;
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dream;sa=shoutbox;xml;" + "delete_shout;" + "canmod=" + canMod[moduleID] + ";" + sessVar + "=" + sessId;
sendXMLDocument(url, send_data);
var shoutID = 0;
while (shoutID !== null)
{
var shoutID = document.getElementById(shout.parentNode.id);
var moduleID = shoutID.parentNode.getAttribute("moduleid");
if (shoutID.parentNode.lastChild)
{
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dream;sa=shoutbox;xml;get_shouts=" + (shoutID.parentNode.lastChild.id.replace("shout_", "") - 1) + ";membercolor=" + memberColor[moduleID] + ";maxcount=" + maxCount[moduleID] + ";shoutboxid=" + shoutboxID[moduleID] + ";textsize=" + textSize[moduleID] + ";parsebbc=" + parseBBC[moduleID] + ";moduleid=" + moduleID + ";maxcount=" + maxCount[moduleID] + ";canmod=" + canMod[moduleID] + ";" + sessVar + "=" + sessId;
getXMLDocument(url, appendShout);
}
element = shoutID.parentNode.childNodes;
var i = element.length;
while (i--)
{
if (i % 2 == 0)
element[i].className = "windowbg2";
else
element[i].className = "windowbg";
}
shoutID.parentNode.removeChild(shoutID);
}
}
Am using the following functions for the sending and getting the XMLHttpRequest as you may have noticed already in the removeShout function above:
// Load an XML document using XMLHttpRequest.
function getXMLDocument(sUrl, funcCallback)
{
if (!window.XMLHttpRequest)
return null;
var oMyDoc = new XMLHttpRequest();
var bAsync = typeof(funcCallback) != 'undefined';
var oCaller = this;
if (bAsync)
{
oMyDoc.onreadystatechange = function () {
if (oMyDoc.readyState != 4)
return;
if (oMyDoc.responseXML != null && oMyDoc.status == 200)
{
if (funcCallback.call)
{
funcCallback.call(oCaller, oMyDoc.responseXML);
}
// A primitive substitute for the call method to support IE 5.0.
else
{
oCaller.tmpMethod = funcCallback;
oCaller.tmpMethod(oMyDoc.responseXML);
delete oCaller.tmpMethod;
}
}
};
}
oMyDoc.open('GET', sUrl, bAsync);
oMyDoc.send(null);
return oMyDoc;
}
// Send a post form to the server using XMLHttpRequest.
function sendXMLDocument(sUrl, sContent, funcCallback)
{
if (!window.XMLHttpRequest)
return false;
var oSendDoc = new window.XMLHttpRequest();
var oCaller = this;
if (typeof(funcCallback) != 'undefined')
{
oSendDoc.onreadystatechange = function () {
if (oSendDoc.readyState != 4)
return;
if (oSendDoc.responseXML != null && oSendDoc.status == 200)
funcCallback.call(oCaller, oSendDoc.responseXML);
else
funcCallback.call(oCaller, false);
};
}
oSendDoc.open('POST', sUrl, true);
if ('setRequestHeader' in oSendDoc)
oSendDoc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
oSendDoc.send(sContent);
return true;
}
Hopefully this is good enough, you can do a view source on it to see the actual HTML, but there are attributes that get added to the Shoutbox tags at runtime so as to be XHTML compliant, etc..
Please let me know if there is anything else you need?
Thanks :)
The code is breaking because shoutID is null in the second of these two lines, the second time through the loop:
var shoutID = document.getElementById(shout.parentNode.id);
var moduleID = shoutID.parentNode.getAttribute("moduleid");
The first of those lines is strange. Why not just use var shoutID = shout.parentNode;?
Also, the moduleId attribute seems to be nowhere around.
What are you trying to achieve with the while loop?