Situation - looping over array of events and assigning properties from JSON parsed
Expected outcome - upload to Parse cloud storage
APIs that I'm using -
https://www.eventbrite.com/developer/v3/formats/event/#ebapi-std:format-event
https://www.parse.com/docs/js/guide
I'm new to Javascript (there actually might be more than one syntax error)
I don't know why I get this error on line 83 when trying to deploy to Parse Cloud Code
What I'm passing in -
var cities = ["San Francisco", "London"];
eventsArray = JSON.parse(httpResponse.text)["events"];
loopEvents(eventsArray);
the whole function as screenshot (syntax highlighting for readability) --> code
the function as text -->
function loopEvents(events) {
if (j == cities.length) {j=0};
for (var i = 0; i < events.length; i++) {
//Parse.Cloud.useMasterKey(); is not needed ATM I think
console.log("assigning properties for " + cities[j] + ".");
list.save({ // saving properties
number: String(i); // ****THIS IS THE LINE 83****
uri: events[i]["resource_uri"];
url: events[i]["url"];
id: events[i]["id"];
name: events[i]["name"]["text"];
description: events[i]["description"]["text"] || "None provided.";
status: events[i]["status"];
capacity: String(events[i]["capacity"]);
logo: events[i]["logo_id"]["logo"] || "http://www.ecolabelindex.com/files/ecolabel-logos-sized/no-logo-provided.png";
start: moment(events[i]["start"]["utc"]);
end: moment(events[i]["end"]["utc"]);
online: events[i]["online_event"];
currency: events[i]["currency"];
ticketClasses: events[i]["ticket_classes"] || "It's freeee!";
ticketClassesNames: events[i]["ticket_classes"]["name"] || "None provided.";
ticketClassesCost: events[i]["ticket_classes"]["cost"] || "It's freeee!";
ticketClassesDescription: events[i]["ticket_classes"]["description"] || "None provided.";
}, {
success: function(list) {
console.log("RIP CloudCode, we had good times!");
},
error: function(list, error) {
console.log("u fuc*ed up, with error: " + error.text + ", son.");
}
});
}
j++;
}
maybe it's all wrong, appreciate the effort and constructive answers ;))) if you need any other info just comment bellow and I'll edit.
EDIT.1 - after replacing ; for , I get the following error
As you're using object, semi-colon ; is not valid syntax.
Remove ; from all the lines inside the object.
number: String(i);
// ^
Use , comma instead.
number: String(i),
// ^
Code
// Notice the comma at the end of each element
list.save({ // saving properties
number: String(i),
uri: events[i]["resource_uri"],
url: events[i]["url"],
id: events[i]["id"],
name: events[i]["name"]["text"],
description: events[i]["description"]["text"] || "None provided.",
status: events[i]["status"],
capacity: String(events[i]["capacity"]),
logo: events[i]["logo_id"]["logo"] || "http://www.ecolabelindex.com/files/ecolabel-logos-sized/no-logo-provided.png",
start: moment(events[i]["start"]["utc"]),
end: moment(events[i]["end"]["utc"]),
online: events[i]["online_event"],
currency: events[i]["currency"],
ticketClasses: events[i]["ticket_classes"] || "It's freeee!",
ticketClassesNames: events[i]["ticket_classes"]["name"] || "None provided.",
ticketClassesCost: events[i]["ticket_classes"]["cost"] || "It's freeee!",
ticketClassesDescription: events[i]["ticket_classes"]["description"] || "None provided."
}, {
See Object creation
ticket classes is actually an array and to access it I had to add a expand parameter to the httpRequest, other than that the code itself was fine, thx Tushar for the syntax correction.
Related
i work on a comunautary bot for discord and i have a probleme in my code
this is my code :
for (let i = 0; i < body.players.length; i++) {
if ((body.players[i].votes >= myToken[0]['palier1'] ) && (body.players[i].votes < myToken[0]['palier2'] )) {
embed50.addFields(
{
name: body.players[i].playername + ' : ',
value: body.players[i].votes + ' votes ! ',
inline: true,
})
}else if((body.players[i].votes >= myToken[0]['palier2'] )) {
embed100.addFields(
{
name: body.players[i].playername + ' : ',
value: body.players[i].votes + ' votes ! ',
inline: true,
})
}
}
and this is my error :
return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid number value", input, expected));
^
ExpectedConstraintError: Invalid number value
at Object.run (/root/bot/node_modules/#sapphire/shapeshift/dist/index.js:727:72)
at /root/bot/node_modules/#sapphire/shapeshift/dist/index.js:113:66
at Array.reduce (<anonymous>)
at NumberValidator.parse (/root/bot/node_modules/#sapphire/shapeshift/dist/index.js:113:29)
at validateFieldLength (/root/bot/node_modules/#discordjs/builders/dist/index.js:146:24)
at EmbedBuilder.addFields (/root/bot/node_modules/#discordjs/builders/dist/index.js:190:5)
at Object.run (/root/bot/commands/topvote.js:111:18)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
constraint: 's.number.lessThanOrEqual',
given: 26,
expected: 'expected <= 25'
}
my first if is okay but the second block my code .....
The stacktrace you posted suggests that the error is coming from a function in the Discord.js library called validateFieldLength.
Looking at the source code for this function in Discord.js it appears the name of this function might be a bit confusing; at first, I thought it was saying the name or value of a field was too long, but it appears that it's actually saying that you're adding too many fields to a single embed, you've added 26 and you're only allowed to add <= 25.
Here is a link to the documentation that goes over the limits for embeds: https://discordjs.guide/popular-topics/embeds.html#embed-limits
I would suggest you track how many fields you've added so far and when you've hit 25 go ahead and create a new embed (keep an array of these) and attach the next batch to that one. Just note that you can only have up to 10 embeds in a single message so you'll have to stop at 250.
I want to take a string in this format I am a level ${level} coder, where ${level} will be some value passed in. But I want only specific word in this sentence bolded. So lets say in this example I want "level" and "coder" bolded. How do I achieve this?
Current Behavior:
Even if I do <b> or <strong> inside `` the tags just get converted to string. It doesn't actually bold the text for me.
Update: This is exactly what I am doing with aws sns. But I want to achieve this with string interpolation.
let snsData = {
Message: < strong > "This is an automated message" < /strong> + '\n' +
"You have successfully uploaded the following:" + '\n'
`File name: ${snsFileName}\n
Number of lines: ${numberOfLines}\n
If there are any issues, please contact XXX for assistance.`,
Subject: 'Successfully Uploaded to XX',
TopicArn: 'XXXXX'
};
Addendum, so this is entirely unique to your instance and I suggest better familiarizing yourself with how string / interpolation and objects work but for the sake of learning, cheers;
const $ = function(id) { return document.getElementById(id) },
level = 'expert',
str = `I am a level <strong>${level} coder</strong>`,
snsFileName = 'testFileNameBlah',
numberOfLines = 99,
snsData = {
Message: '<strong>This is an automated message</strong><br/>' +
'You have successfully uploaded the following:<br/>' +
`File name: <strong>${snsFileName}</strong><br/>
Number of lines: <strong>${numberOfLines}</strong><br/>` +
'If there are any issues, please contact XXX for assistance.<br/>',
Subject: 'Successfully Uploaded to XX',
TopicArn: 'XXXXX'
};
$('blah').innerHTML = str + '<hr>';
$('fixme').innerHTML = snsData.Message + snsData.Subject;
<span id="blah"></span>
<h2>Addendum</h2>
<p id="fixme"></p>
I'm working on a CLI program, based on nodejs and the npm package "prompt".
Let say I want to have this prompt, putting the input in a variable pet:
Choose a pet:
(1) - Cat
(2) - Dog
(3) - Fish
(4) - Rabbit
(5) - Rat
: >
Basically I did the functionality, but I'm having the following problems:
If I use the conform function for custom validation - then my custom message - the multiline text - never appears. The name of the variable - pet - only appears. But I want to have validation, cause I want to make sure the user won't enter 333 for example.
If I remove the conform custom validation - I can have multiline text, but then something else happens: the blinking rectangle, where the entering happens, overlaps with the multiline text. And I can't make it blink after the last line of the multiline message.
(In the above example the blinking happens over the digit 5.)
Any idea how to resolve the two issues I have ? ... :)
================== EDIT: Added code samples ===================
This is how I generate the multiline text:
// generate the multiline text ..
var petsMessage = 'Choose a pet: \n';
var pets = [...];
for(var i = 0, l = pets.length; i < l; i++) {
petsMessage += ' (' + (i+1) + ') - ' + pets[i] + "\n";
}
This is how I generate the prompt with multiline text, but no validation:
// define the prompt stuff ..
var promptInfo = {
properties: {
Pet: {
message: petsMessage,
required: true
},
}
};
And this is with validation, but multiline message not working:
// define the prompt stuff ..
var promptInfo = [
{
name: 'Pet',
message: petsMessage,
required: true,
conform: function(value) {
value = parseInt(value);
if(value > 0 && value < pets.length) {
return true;
} else {
return false;
}
}
}
];
I believe the problem was that in the second snippet with the validation you assign the actual question in the message property, you should assign it in the description. The message property refers to error message. Try this please:
var petsMessage = 'Choose a pet: \n';
var pets = ["dog","cat","frog"];
for(var i = 0, l = pets.length; i < l; i++) {
petsMessage += '\t (' + (i+1) + ') - ' + pets[i] + "\n";
}
var prompt = require('prompt');
var promptInfo = [
{
name: 'Pet',
description: petsMessage,
required: true,
message: 'Options allowed:: 1'+'-'+pets.length,
conform: function(value) {
value = parseInt(value);
return value > 0 && value <= pets.length
}
}
];
prompt.start();
prompt.get(promptInfo, function (err, result) {
console.log('you Choose',result,'::::',pets[result.Pet-1])
});
Actually, the solution from "alex-rokabills" is not perfect too :( ... It's definitely better, but I still see issues.
If I use small amount of items then it's OK:
But if the number grows a little bit:
And for big prompts:
Also - can I get rid of the "prompt:" at the begining ? ...
as the title says I need to extract content out of long text with certain fields.
I have this text as below
Name: David Jones
Office Address: 148 Hulala Street Date: 24/11/2013
Agent No: 1234,
Address: 259 Yolo Road Start Date: 22/11/2013 Due Date: 29/11/2013
Type: Human Properties: None Ago: 29
And I have these labels for specific fields in the text
Name, Office Address, Date, Agent No, Address, Type, Properties, Age
And the result I want to get is
Name: 'David Jones',
Office Address: '148 Hulala Street',
Date: '24/11/2013',
Agent No: '1234',
Address: '259 Yolo Road',
Type: 'Human'
Properties: 'None',
Age: ''
that has completely parsed the content with each field. Important thing to note here is the original text can possibly have typo (E.g., Ago instead of Age) and extra fields that do not exist in the list of labels (E.g., Start Date and Due Date do not exist in the label list). So the code will ignore any un-matching text and try to find only matching result.
I tried to resolve this by going through loops for each line, check if a line contains the field, and see if the line also contains more fields.
Currently I have the following code.
structure = ['Name','Office Address','Date','Agent No','Address','Type','Properties','Age'];
obj = {};
for (i = 0; i < textLines.length; i++) {
matchingFields = [];
for (j = 0; j < structure.length; j++) {
if (textLines[i].indexOf(structure[j] + ':') !== -1) {
if (matchingFields.length === 0 && textLines[i].indexOf(structure[j] + ':') === 0) {
matchingFields.push(structure[j]);
structure.splice(structure.indexOf(structure[j--]), 1);
} else if (textLines[i].indexOf(structure[j] + ':') > textLines[i].indexOf(matchingFields[matchingFields.length-1])) {
matchingFields.push(structure[j]);
structure.splice(structure.indexOf(structure[j--]), 1);
}
}
for (j = 0; j < matchingFields.length; j++) {
if (j !== matchingFields.length-1) {
obj[matchingFields[j]] = textLines[i].slice(textLines[i].indexOf(matchingFields[j]) + matchingFields[j].length, textLines[i].indexOf(matchingFields[j+1]));
} else {
obj[matchingFields[j]] = textLines[i].slice(textLines[i].indexOf(matchingFields[j]) + matchingFields[j].length);
}
obj[matchingFields[j]] = obj[matchingFields[j]].replace(':', '');
if (obj[matchingFields[j]].indexOf(' ') === 0) {
obj[matchingFields[j]] = obj[matchingFields[j]].replace(' ', '');
}
if (obj[matchingFields[j]].charAt(obj[matchingFields[j]].length-1) === ' ') {
obj[matchingFields[j]] = obj[matchingFields[j]].slice(0, obj[matchingFields[j]].length-1);
}
}
}
In some cases it could work fine but with 'Office Address: ' and 'Address: ' existing value for 'Office Address:' goes into 'Address:'. Besides, the code looks messy and ugly. Also seems like kind of brute forcing.
I guess there should be a better way. For example using regular expression or something similar. but no external library.
If you have any idea I will appreciate it for sharing.
Assuming the properties are separated by newline characters, you create an object mapping each attribute to its value using:
var str = "Name: David Jones\nOffice Address: 148 Hulala Street\nDate: 24/11/2013\nAgent No: 1234,\nAddress: 259 Yolo Road\\nType: Human Properties: None Age: 29";
var output = {};
str.split(/\n/).forEach(function(item){
var match = (item.match(/([A-Za-z\s]*):\s([A-Za-z0-9\s\/]*)/));
output[match[1]] = match[2];
});
console.log(output)
This may help:
> a.substr(a.indexOf("Name"), a.indexOf("Office Address")).split(":")
["Name", " David Jones "]
from my code behind i am passing this to client side script
C# code behind
*note if i comment the below line than i dont get js error.*
if (btnDelete != null)
{
btnDelete.Attributes["onclick"] = String.Format("return DeleteRow('{0}', '{1}', '{2}', '{3}');", e.Row.ClientID, e.Row.RowIndex, DataBinder.Eval(e.Row.DataItem, "Id"), DataBinder.Eval(e.Row.DataItem, "Name"));
}
//javascript
function DeleteRow(rowId, rowIdx, Id, Name) {
var result = confirm('Are you sure you want to delete this record? \n\n Id: ' + Id + "\n Name: " + Name);
if (!result)
HighlightRow(rowId, rowIdx % 2 ? "#DEEEE9" : "#FFFFFF");
return result;
}
error message:
Message: Unterminated string constant
Line: 1280
Char: 180
Code: 0
URI: http://localhost:4964/admin/default.aspx
Message: Unterminated string constant
Line: 1341
Char: 178
Code: 0
URI: http://localhost:4964/default.aspx
Message: Expected ')'
Line: 1401
Char: 152
Code: 0
URI: http://localhost:4964/default.aspx
It's hard to tell from your question, but it sounds like the values that are being returned are including the single quote character (apostrophe) which would end your string in the resulting javascript.
What is the code that is being generated for the lines that are throwing the error?
When similar things have happened to me it resulted in something like:
return DeleteRow('1', '2', 'abscde', 'Mc'Adams');
Which would cause an error because of the value Mc'Adams. If that is the case then you'll have to send your data through a method that escapes values that would otherwise corrupt your javascript.
You've used mixed single and double quotes. Change the line here;
var result = confirm('Are you sure you want to delete this record? \n\n Id: ' + Id + '\n Name: ' + Name)
here is how i abel to fix it:
btnDelete.Attributes["onclick"] = String.Format("return DeleteRow('{0}', '{1}', '{2}', '{3}');", e.Row.ClientID, e.Row.RowIndex, DataBinder.Eval(e.Row.DataItem, "Id"), DataBinder.Eval(e.Row.DataItem, "Name").ToString().Trim().Replace("'", "\\'")));