I have the following javascript that works perfectly good (with jquery):
function(test) {
var neuroimages = viewer.loadImageFromJSON('../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold');
return neuroimages;
};
Now I want to use a variable (lets say picture) instead of the '../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold' and format the code accordingly:
function(test) {
picture = "'../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'";
neuroimages = viewer.loadImageFromJSON(picture);
return neuroimages;
};
This does not work.
Neither does this:
function(test) {
pic1 = "'../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'";
pic2 = "'neg_subj_val_5'";
pic3 = "'hot and cold'";
neuroimages = viewer.loadImageFromJSON(pic1, pic2, pic3);
return neuroimages;
};
What am I doing wrong there?
I tried google and several sites with no success. Not to mention that I'm quiet a beginner with Java and already near insanity.
You are almost right with the second example. Here you should only specify one piece of data for each variable (at least in your case, but there are ways to specify many pieces of data in a single variable such as arrays and objects). Also you only need to have one set of quotes surrounding each string (doesn't matter whether they are single or double quotes as long as they match). Also, precede your variables with the 'var' keyword unless you want them to be global.
function(test) {
var pic1 = "../data/new/res_neg_subj_val_5.nii.json";
var pic2 = "neg_subj_val_5";
var pic3 = "hot and cold";
neuroimages = viewer.loadImageFromJSON(pic1, pic2, pic3);
return neuroimages;
};
Making your first attempt work is a little more tricky as you are passing an array to a function that expects three distinct variables. You do it like this:
function(test) {
var picture = ['../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'];
neuroimages = viewer.loadImageFromJSON.apply(viewer, picture);
return neuroimages;
};
You're trying to initialize an array here, but you need to have a string instead. Try changing this:
picture = "'../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'";
to:
picture = "'../data/new/res_neg_subj_val_5.nii.json';
You are not specifying if viewer.loadImageFromJSON() can accept an array, instead of a string. If it can, you could do something like:
picture = ['../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'];
Check here on how to initialize arrays in Javascript:
http://www.w3schools.com/js/js_obj_array.asp
If you need more information on the issue, please attach the code for loadImageFromJSON(), so that we know how this function handles input and output
Related
The name list is supposedly as below:
Rose : 35621548
Jack : 32658495
Lita : 63259547
Seth : 27956431
Cathy: 75821456
Given you have a variable as StudentCode that contains the list above (I think const will do! Like:
const StudentCode = {
[Jack]: [32658495],
[Rose]: [35621548],
[Lita]: [63259547],
[Seth]: [27956431],
[Cathy]:[75821456],
};
)
So here are the questions:
1st: Ho can I define them in URL below:
https://www.mylist.com/student=?StudentCode
So the link for example for Jack will be:
https://www.mylist.com/student=?32658495
The URL is imaginary. Don't click on it please.
2nd: By the way the overall list is above 800 people and I'm planning to save an external .js file to be called within the current code. So tell me about that too. Thanks a million
Given
const StudentCode = {
"Jack": "32658495",
"Rose": "35621548",
"Lita": "63259547",
"Seth": "27956431",
"Cathy": "75821456",
};
You can construct urls like:
const urls = Object.values(StudentCode).map((c) => `https://www.mylist.com?student=${c}`)
// urls: ['https://www.mylist.com?student=32658495', 'https://www.mylist.com?student=35621548', 'https://www.mylist.com?student=63259547', 'https://www.mylist.com?student=27956431', 'https://www.mylist.com?student=75821456']
To get the url for a specific student simply do:
const url = `https://www.mylist.com?student=${StudentCode["Jack"]}`
// url: 'https://www.mylist.com?student=32658495'
Not sure I understand your second question - 800 is a rather low number so will not be any performance issues with it if that is what you are asking?
The properties of the object (after the trailing comma is removed) can be looped through using a for-in loop, (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
This gives references to each key of the array and the value held in that key can be referenced using objectName[key], Thus you will loop through your object using something like:
for (key in StudentCode) {
keyString = key; // e.g = "Jack"
keyValue = StudentCode[key]; // e.g. = 32658495
// build the urls and links
}
to build the urls, string template literals will simplify the process (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) allowing you to substitute values in your string. e.g.:
url = `https://www.mylist.com/student=?${StudentCode[key]`}
Note the use of back ticks and ${} for the substitutions.
Lastly, to build active links, create an element and sets its innerHTML property to markup built using further string template literals:
let link = `<a href=${url}>${keyValue}</a>`
These steps are combined in the working snippet here:
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const studentLinks = [];
for (key in StudentCode) {
let url = `https://www.mylist.com/student=?${StudentCode[key]}`;
console.log(url);
studentLinks.push(`<a href href="url">${key}</a>`)
}
let output= document.createElement('div');
output.innerHTML = studentLinks.join("<br>");
document.body.appendChild(output);
The method I use I need to put +13 and -1 inside the calculation when searching the position of each part of the text (const Before and const After), is there a more reliable and correct way?
const PositionBefore = TextScript.indexOf(Before)+13;
const PositionAfter = TextScript.indexOf(After)-1;
My fear is that for some reason the search text changes and I forget to change the numbers for the calculation and this causes an error in the retrieved text.
The part of text i'm return is date and hour:
2021-08-31 19:12:08
function Clock() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Clock');
var url = 'https://int.soccerway.com/';
const contentText = UrlFetchApp.fetch(url).getContentText();
const $ = Cheerio.load(contentText);
const Before = '"timestamp":"';
const After = '});\n block.registerForCallbacks();';
var ElementSelect = $('script:contains(' + Before + ')');
var TextScript = ElementSelect.html().replace("\n","");
const PositionBefore = TextScript.indexOf(Before)+13;
const PositionAfter = TextScript.indexOf(After)-1;
sheet.getRange(1, 1).setValue(TextScript.substring(PositionBefore, PositionAfter));
}
Example full text colected in var TextScript:
(function() {
var block = new HomeMatchesBlock('block_home_matches_31', 'block_home_matches', {"block_service_id":"home_index_block_homematches","date":"2021-08-31","display":"all","timestamp":"2021-08-31 19:12:08"});
block.registerForCallbacks();
$('block_home_matches_31_1_1').observe('click', function() { block.filterContent({"display":"all"}); }.bind(block));
$('block_home_matches_31_1_2').observe('click', function() { block.filterContent({"display":"now_playing"}); }.bind(block));
block.setAttribute('colspan_left', 2);
block.setAttribute('colspan_right', 2);
TimestampFormatter.format('block_home_matches_31');
})();
There is no way to eliminate the risk of structural changes to the source content.
You can take some steps to minimize the likelihood that you forget to change your code - for example, by removing the need for hard-coded +13 and -1. But there can be other reasons for your code to fail, beyond that.
It's probably more important to make it extremely obvious when your code does fail.
Consider the following sample (which does not use Cheerio, for simplicity):
function demoHandler() {
var url = 'https://int.soccerway.com/';
const contentText = UrlFetchApp.fetch(url).getContentText();
var matchedJsonString = contentText.match(/{.*?"timestamp".*?}/)[0];
if ( matchedJsonString ) {
try {
var json = JSON.parse(matchedJsonString);
} catch(err) {
console.log( err ); // "SyntaxError..."
}
console.log(json.timestamp)
} else {
consle.log( 'Something went terribly wrong...' )
}
}
When you run the above function it prints the following to the console:
2021-08-31 23:18:46
It does this by assuming the key value of "timestamp" is part of a JSON string, starting with { and ending with }.
You can therefore extract this JSON string and convert it to a JavaScript object and then access the timestamp value directly, without needing to handle substrings.
If the JSON is not valid you will get an explicit error similar to this:
[SyntaxError: Unexpected token c in JSON at position 0]
Scraping web page data almost always has these types of risk: Your code can be brittle and break easily if the source structure changes without warning. Just try to make suc changes as noticeable as possible. In your case, write the errors to your spreadsheet and make it really obvious (red, bold, etc.).
And make good use of try...catch statements. See: try...catch
Website that I'm making is in two different languages each data is saved in mongodb with prefix _nl or _en
With a url I need to be able to set up language like that:
http://localhost/en/This-Is-English-Head/This-Is-English-Sub
My code look like that:
var headPage = req.params.headPage;
var subPage = req.params.subPage;
var slug = 'name';
var slugSub = 'subPages.slug_en';
var myObject = {};
myObject[slugSub] = subPage;
myObject[slug] = headPage;
console.log(myObject);
Site.find(myObject,
function (err, pages) {
var Pages = {};
pages.forEach(function (page) {
Pages[page._id] = page;
});
console.log(Pages);
});
After console.log it I get following:
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Is you can see objectname subPages.slug_en is seen as a String insteed of object name..
I know that javascript does not support underscores(I guess?) but I'm still looking for a fix, otherwise i'll be forced to change all underscores in my db to different character...
Edit:
The final result of console.log need to be:
{ subPages.slug_en: 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Insteed of :
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Otherwise it does not work
The reason you are seeing 'subPages.slug_en' (with string quotes) is because of the . in the object key, not the underscore.
Underscores are definitely supported in object keys without quoting.
Using subPages.slug_en (without string quotes) would require you to have an object as follows:
{ subPages: {slug_en: 'This-Is-English-Sub'},
name: 'This-Is-English-Head' }
Which you could set with the following:
myObject['subPages']['slug_en'] = subPage;
Or simply:
myObject.subPages.slug_en = subPage;
I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}
In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.
the problem is i want to shorten my code by calling a variable using other variable's value
long working version:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
switch(this.id){
case 'russia':
active_country_lift(this.id,russia[0])
break
case 'switzerland':
active_country_lift(this.id,switzerland[0])
break
}
})
it will get the id of mouseovered then check if it matched one of the variable by using switch
what i want to obtain is something like this:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
active_country_lift(this.id,this.id[0])
})
of course the above code wouldn't work but is there a workaround for this?
UPDATE: Arun's answer worked and ill accept it soon and as for the comments requesting for the full code, here's a chunk of it after i applied Arun's
var countries = {
russia: ['-15px'],
switzerland: ['-5px']
}
$('.country_inactive').mouseover(function(){
active_country_lift(this.id, countries[this.id][0])
})
function active_country_lift(country, country_top){
if(!$('#'+country+'_active').hasClass('active')){
$('#'+country+'_active').stop().fadeIn(100).animate({
'top' : country_top
}, 200)
$('#'+country).stop().fadeOut(100)
}
}
it will be used for a world map, feel free to make any suggestions for making it more dynamic
You can store the country info in an object like a key value pair, then use bracket notation to access it dynamically
var countries = {
russia: new Array('-15px'),
switzerland: new Array('-5px')
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id][0])
})
If you don't have multiple values then
var countries = {
russia: '-15px',
switzerland: '-5px'
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id])
})
try using eval() function
var russia = new Array('-15px')
var switzerland = new Array('-5px')
$('.country').mouseover(function(){
active_country_lift(this.id,eval(this.id)[0])
})