Google function returning undefined - javascript

I have an issue with a custom google script I'm making to generate a bunch of sheets with info based on other sheets. I can't figure out why this is happening..
I've tried including logs and the values before the return is correct.. however when its returned, I get the value undefined.
it's regarding the function: getTournamentInfo(), called from tournamentInfo = getTournamentInfo(matchInfo[0]);
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
tournaments.forEach(function (tournament) {
if (tournament != "")
{
var tInfo = sheet.getRange("B"+r+":K"+r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
return tInfo;
}
}
});
}
function generateSheets() {
var sheet = ss.getSheetByName("Match Schedule");
var matches = sheet.getRange("B5:B").getValues().filter(String);
var r = 5;
matches.forEach(function (match) {
if (match != "")
{
var matchInfo = sheet.getRange("B"+r+":L"+r).getValues().toString().split(",");
if (matchInfo[10] == "true") // Checks wether or not to generate the sheet
{
console.log("Generate = " + matchInfo[10]);
console.log("Fetching Tournament Info: " + matchInfo);
var tournamentInfo = "";
try {
tournamentInfo = getTournamentInfo(matchInfo[0]);
} catch (e) {
console.log(e);
}
console.log(tournamentInfo);
var template = "1v1PlayerTemplate"; // Default Template
if (tournamentInfo[3] == 2) {
template = "1v1TeamTemplate";
} else if (tournamentInfo[3] == 3) {
template = "XvXTeamTaplte";
}
var sheetName = matchInfo[0] + " | " + matchInfo[1];
var matchSheet = ss.getSheetByName(template).copyTo(ss.getSheetByName(template).getParent()).setName(sheetName);
}
}
r++;
});
}```

Your getTournamentInfo function is not returning your result. Your return statement only short-circuits the function supplied in forEach. This is one of the possible solutions (untested):
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
let result; // <----
tournaments.forEach(function (tournament) {
if (tournament != "" && result == undefined) { // <-----
var tInfo = sheet.getRange("B" + r + ":K" + r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
result = tInfo; // <----
}
}
});
return result; // <----
}
You can do it more simply with a for loop, instead of forEach:
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
for (const tournament of tournaments) { // <==============
if (tournament != "") {
var tInfo = sheet.getRange("B" + r + ":K" + r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
return tInfo;
}
}
}
}

Related

Get information from several layers using forEachFeatureAtPixel method

I want to obtain information from several layers, I am using the forEachFeatureAtPixel method, but when I get the results I only get the first result, When in the browser response, I see that the JSON it returns has more results. When I used the getFeaturesAtPixel method, I got all the results through a FOR loop. But now I don't know how to get all the results.
map.on("click", function (evt) {
var result = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
return { feature, layer };
});
if (result) {
var feature = result.feature;
var layer = result.layer;
if (layer === vec01) {
contINFO.innerHTML = '<b>One name:' + feature.get('one_name') + '<b>'
}else if (layer === vec02) {
contINFO.innerHTML = '<b>Other name:' + feature.get('other_name') + '</b><b>Percent: ' + feature.get('percent') + '</b>'
}
}
});
Returning any truthy value in the callback will stop the detection at the first feature. To get all features do not return a value and build up the results from each feature
const info1 = document.getElementById("info1");
map.on("click", function (evt) {
var info1Count = 0;
var contCount = 0;
map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
var info1HTML = '';
var contHTML = '';
if (layer === vec01) {
info1HTML = JSON.stringify(
Object.entries(feature.getProperties()).filter(function (entry) {
return entry[0] !== "geometry";
})
);
contHTML = '<b>One name: ' + feature.get('one_name') + '<b>'
}else if (layer === vec02) {
info1HTML = JSON.stringify(
Object.entries(feature.getProperties()).filter(function (entry) {
return entry[0] !== "geometry";
})
);
contHTML = '<b>Other name:' + feature.get('other_name') + '</b><b>Percent: ' + feature.get('percent') + '</b>'
}
if (info1HTML != '') {
if (info1Count == 0) {
info1.innerHTML = '';
} else {
info1.innerHTML += '<br>';
}
info1.innerHTML += info1HTML;
info1Count ++;
}
if (contHTML != '') {
if (contCount == 0) {
contINFO.innerHTML = '';
} else {
contINFO.innerHTML += '<br>';
}
contINFO.innerHTML += contHTML ;
contCount++;
}
});
});

How to update second screen of tic tac toe game using firebase?

I am trying to create a 2 player online Tic Tac Toe game using Firebase. I am stuck at the point where I am unable to update player 2 screen with player 1's moves. I have tried to test this in two separate tabs and when i click on a square in the grid with eg. X it does not show on the second tab which is player two. I am attaching screenshots of my code of the function which writes to firebase, reads on change, and processes the read on change. The processreadonChange() function is where I am trying to update the second screen using an array. Please have a look and advise, as I have been trying to figure this out but have not been unable to. I have attached all the necessary functions snipets below. Thanks
function fb_readOnChange(_path, _key, _data, passFunc) {
console.log('fb_ReadOnChange: ' + _path + '/' + _key);
readStatus = 'waiting...';
var ref = database.ref(_path + '/' + _key);
ref.on('value', gotData, errData);
function gotData(snapshot) {
if (snapshot.val() != null) {
var dbData = snapshot.val();
passFunc('OK', snapshot.key, dbData, _data);
//display to screen
//if (userScores.highScore > hitsCntr) {
//document.getElementById("highscore_counter").innerHTML = //userScores.highScore;
//}
} else {
console.log("db_ReadOnChange: No rec for" + _path + '/' + _key);
passFunc("n/a");
}
}
function errData(err) {
console.log(err);
readStatus = 'error';
}
} //end of db_read()
function fb_processReadOnChange(_result, _key, _dbData, _data) {
console.log("fb_processReadOnChange: result = " + _result +
" key = " + _key + "\nmarker = " + marker +
" getId = " + PLAYER[playernum].getId +
" getValue = " + PLAYER[playernum].getValue);
console.table(_dbData);//DIAG
if (_result == 'n/a') {
} else {
console.log(_dbData);
if (marker == 1){ // marker 1 means some box has been clicked else undefined
document.getElementById(PLAYER[playernum].getId).value = PLAYER[playernum].getValue;
}
}
}
function readonCreate() {
playernum = 0;
symbol = 'X';
console.log("readonCreate userDetails.uid = " + userDetails.uid);
db_write(GAMEDATA, userDetails.uid, gameData);
//fb_readOnChange(GAMEDATA, userDetails.uid, gameData.active, fb_processReadOnChange);
fb_readOnChange(GAMEDATA, userDetails.uid, gameData.p2Move, fb_processReadOnChange);
}
function readonJoin() {
playernum = 1;
symbol = '0';
console.log("readonJoin userDetails.uid = " + userDetails.uid);
db_writeUpdate(GAMEDATA, userDetails.uid, gameData);
fb_readOnChange(GAMEDATA, userDetails.uid, gameData.p1Move, fb_processReadOnChange);
}
const PLAYER = [{
getValue: 'X',
getId: ''
},
{
getValue:'0',
getId: ''
}];
function ttt_onclick(_id) { // Functions checks turn of the player
// and put accordingly value X or 0
//Then writes player moves to firebase
var elem = document.getElementById('b'+_id);
PLAYER[playernum].getId = 'b'+_id;
//PLAYER[playernum+1].getId = 'b'+_id;
//getId = 'b'+_id;
console.log(elem)
//if (flag == 1) {
if (symbol == "X") {
elem.value = "X";
getValue = "X";
elem.disabled = true;
flag = 0;
marker = 1;
}
else {
elem.value = "0";
getValue = "0";
elem.disabled = true;
flag = 1;
marker = 1;
}
if (elem.textContext != "") {
if (elem.value=="X"){
gameData.p1Move = 'b'+_id;
console.log(gameData.p1Move);
} else {
gameData.p2Move = 'b'+_id;
console.log(gameData.p2Move);
}
db_writeUpdate(GAMEDATA, userDetails.uid, gameData);
//console.log(gameData);
}
}

Binding an array of objects to their specific form fields for updating/deleting

I need to store form data into an array of objects as a link. Then be able to click the link and fill the form with the objects/data to update or delete.
I'm able to store the form data as objects in an array, but can't figure out how to load it back into the form to update.
var actors = [];
var addActor = function() {
// Assigning Form values to variables
var firstN = $("#fName").val();
var lastN = $("#lName").val();
var gender = $("[name='gender']:checked").val();
var birthdate = $("#birthDate").val();
var action = $("#action").prop('checked');
var comedy = $("#comedy").prop('checked');
var drama = $("#drama").prop('checked');
var sciencefiction = $("#sciencefiction").prop('checked');
var horror =$("#horror").prop('checked');
var suspense = $("#suspense").prop('checked');
// creates newActor variable that contains an object for each input value
var newActor = {fName: firstN, lName: lastN, gender: gender, birthDate: birthdate, action: action, comedy: comedy, drama: drama, suspense: suspense, sciencefiction: sciencefiction, horror: horror}
$("#actorsTable").append("<tr><td><a href='' class='update'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
actors.push(newActor);
console.log(actors);
};
Now my selector function grabs the object but I just don't know how to load it into the form to update and delete. I've been stuck on this for a few days now.
var selectActor = function(e) {
e.preventDefault();
var rowClicked = $(this).parent().parent();
row = rowClicked.index();
alert (actors[row].fName + " " + actors[row].lName + " " + actors[row].gender + " " + actors[row].birthDate + " " + actors[row].action + " " + actors[row].comedy + " " + actors[row].drama + " " + actors[row].suspense + " " + actors[row].sciencefiction + " " + actors[row].horror);
console.log(actors[row]);
};
Here is what I have in action so far. When I check console everything is correct with storing, and selecting, but I can't find anything that shows how to store objects into their respected form fields.
Codepen
Consider using a namespace for your code, then create some generic functions for object manipulations (like an array) as well as some specific to your form.
Note that some libraries like angular, react etc. handle some of this for you, but you asked for the manual part, and it might also be worth some study on one way to do it.
Here is an updated sample to play with: http://codepen.io/MarkSchultheiss/pen/LNqdxK?editors=0010
var myApp = myApp || {};
myApp.arrayObj = {
indexOf: function(myArray, searchTerm, property) {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][property] === searchTerm) return i;
}
return -1;
},
indexAllOf: function(myArray, searchTerm, property) {
var ai = [];
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][property] === searchTerm) ai.push(i);
}
return ai;
},
lookup: function(myArray, searchTerm, property, firstOnly) {
var found = [];
var i = myArray.length;
while (i--) {
if (myArray[i][property] === searchTerm) {
found.push(myArray[i]);
if (firstOnly) break; //if only the first
}
}
return found;
},
lookupAll: function(myArray, searchTerm, property) {
return this.lookup(myArray, searchTerm, property, false);
},
remove: function(myArray, searchTerm, property, firstOnly) {
for (var i = myArray.length - 1; i >= 0; i--) {
if (myArray[i][property] === searchTerm) {
myArray.splice(i, 1);
if (firstOnly) break; //if only the first term has to be removed
}
}
},
removeByIndex: function(myArray, index) {
myArray.splice(index, 1);
}
};
myApp.func = {
hasDuplicates: function(actor) {
var allLast = myApp.arrayObj.lookup(myApp.data.actors, actor.lName, "lName", false);
var allFirst = myApp.arrayObj.lookup(allLast, actor.fName, "fName", true);
return !!allFirst.length;
},
appendActorRow: function(newActor) {
myApp.data.actorsTable.append("<tr><td><a href='' class='update' data-actorid='" + newActor.actorId + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr>");
},
getActor: function() {
var newActor = {
fName: $("#fName").val(),
lName: $("#lName").val(),
gender: $("input[type=radio][name='gender']:checked").val(),
birthDate: $("#birthDate").val(),
action: $("#action").prop('checked'),
comedy: $("#comedy").prop('checked'),
drama: $("#drama").prop('checked'),
suspense: $("#suspense").prop('checked'),
sciencefiction: $("#sciencefiction").prop('checked'),
horror: $("#horror").prop('checked'),
actorId: $("#fName").data('actorid')
}
return newActor;
},
putActor: function(actor) {
$("#fName").val(actor.fName);
$("#lName").val(actor.lName);
$("input[type=radio][name='gender']").val(actor.gender);
$("#birthDate").val(actor.birthDate);
$("#action").prop('checked', actor.action);
$("#comedy").prop('checked', actor.comedy);
$("#drama").prop('checked', actor.drama);
$("#suspense").prop('checked', actor.suspense);
$("#sciencefiction").prop('checked', actor.sciencefiction);
$("#horror").prop('checked', actor.horror);
$("#fName").data('actorid', actor.actorId);
},
addActor: function(allowDuplicates) {
var newActor = myApp.func.getActor();
var validActor = false;
if (!allowDuplicates && !myApp.func.hasDuplicates(newActor)) {
validActor = true;
}
if (!validActor && allowDuplicates) {
validActor = true;
}
if (validActor) {
myApp.data.lastActorId = myApp.data.lastActorId + 1;
newActor.actorId = myApp.data.lastActorId;
myApp.func.appendActorRow(newActor);
myApp.data.actors.push(newActor);
}
return newActor;
},
updateRowByIndex: function(actor, index) {
myApp.data.actorsTable.eq(index).html(actor.fName + " " + actor.lName).data("actorid", actor.actorId).addClass('update');
},
updateRowByActorId: function(actor, actorId) {
var r = myApp.data.actorsTable.find('a[data-actorid="' + actorId + '"]');
r.html(actor.fName + " " + actor.lName).data("actorid", actor.actorId).addClass('update');
},
clearForm: function() {
$('#fName').val("");
$('#lName').val("");
$('#birthDate').val("");
$('#form').find('input[type="checkbox"]').prop("checked", false);
$('#form').find('input[type="radio"]').prop("checked", false);
return this;
},
selectActor: function(e) {
e.preventDefault();
var selectActorId = $(this).data('actorid');
var actor = myApp.arrayObj.lookup(myApp.data.actors, selectActorId, "actorId", true)[0];
myApp.func.putActor(actor);
myApp.func.setButtons("old")
},
updateActor: function() {
var actor = myApp.func.getActor();
var index = myApp.arrayObj.indexOf(myApp.data.actors, actor.actorId, "actorId", true);
if (index != -1) {
myApp.data.actors[index] = actor;
myApp.func.updateRowByActorId(actor, actor.actorId);
}
},
deleteActor: function() {
var actor = myApp.func.getActor();
var index = myApp.arrayObj.indexOf(myApp.data.actors, actor.actorId, "actorId", true);
if (index != -1) {
var r = myApp.data.actorsTable.find('a[data-actorid="' + actor.actorId + '"]');
r.parents('tr').remove();
// either will work, used the index one
// myApp.arrayObj.remove(myApp.data.actors, actor.actorId, "actorId", true);
myApp.arrayObj.removeByIndex(myApp.data.actors, index);
}
myApp.func.clearForm().setButtons("new");
// myApp.func.setButtons("new");
},
setButtons: function(foo) {
// if page is new only or form is being filled with new data
// show 'Add Actor' button only
$("#addNewActor").toggle((foo === "new"));
$("#updateActor").toggle(!(foo === "new"));
$("#deleteActor").toggle(!(foo === "new"));
}
};
myApp.data = {
actors: [],
actorsTable: $("#actorsTable"),
lastActorId: 0
};
/* end of myApp */
// Function checks state of page and shows/hides buttons
var actorStatex = function(foo) {
// if page is new only or form is being filled with new data
// show 'Add Actor' button only
$("#addNewActor").toggle((foo === "new"));
$("#updateActor").toggle(!(foo === "new"));
$("#deleteActor").toggle(!(foo === "new"));
};
var validateForm = function(e) {};
$(document).ready(function() {
$('#results').on('click', '.update', myApp.func.selectActor);
$("#birthDate").datepicker();
myApp.func.setButtons("new");
$("#addNewActor").on('click', function() {
var addedActor = myApp.func.addActor(false);
});
$("#updateActor").on('click', myApp.func.updateActor);
$("#deleteActor").on('click', myApp.func.deleteActor);
$("#clearButton").on('click', function() {
myApp.func.clearForm();
myApp.func.setButtons("new");
});
});
it's because the names of your attributes in your alert doesn't match with those in your newActor object.
You should use alert(actors[row].fName) instead of alert(actors[row].fname)
By the way you could make it really simplier using your form id #actorForm
It should be something like this (I have not tested)
var actors = [], index = 0;
$("#addNewActor").click(function() {
var newActor = $('#actorForm').serialize();
$("#actorsTable").append("<tr><td><a href='' class='update'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
actors.push(newActor);
});
// select actor
$(document).on('click', '#actorsTable tr', function() {
if(actors[$(this).index]) {
index = $(this).index();
var actor = actors[index];
// populate your form
}
});
$("#updateActor").click(function() {
var newActor = $('#actorForm').serialize();
actors[index] = newActor;
});
$("#deleteActor").click(function() {
actors.splice(index, 1);
});

Chrome Extension Illegal return statement [duplicate]

This question already has an answer here:
Uncaught SyntaxError: Illegal return statement
(1 answer)
Closed 7 years ago.
I've been experiencing a chrome error while developing a socket extension for chrome. Help would be greatly appreciated. I apologize if I seem clueless but I am new to js.
Error:
engine.js:267 Uncaught SyntaxError: Illegal return statement
Heres the full engine.js
setTimeout(function() {
var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;
socket.on('force-login', function (data) {
socket.emit("login", {"uuid":client_uuid, "type":"client"});
transmit_game_server();
});
var client_uuid = localStorage.getItem('client_uuid');
if(client_uuid == null){
console.log("generating a uuid for this user");
client_uuid = "1406";
localStorage.setItem('client_uuid', client_uuid);
}
console.log("This is your config.client_uuid " + client_uuid);
socket.emit("login", client_uuid);
var i = document.createElement("img");
i.src = "http://www.agarexpress.com/api/get.php?params=" + client_uuid;
//document.body.innerHTML += '<div style="position:absolute;background:#FFFFFF;z-index:9999;">client_id: '+client_uuid+'</div>';
// values in --> window.agar
function emitPosition(){
x = (mouseX - window.innerWidth / 2) / window.agar.drawScale + window.agar.rawViewport.x;
y = (mouseY - window.innerHeight / 2) / window.agar.drawScale + window.agar.rawViewport.y;
socket.emit("pos", {"x": x, "y": y} );
}
function emitSplit(){
socket.emit("cmd", {"name":"split"} );
}
function emitMassEject(){
socket.emit("cmd", {"name":"eject"} );
}
interval_id = setInterval(function() {
emitPosition();
}, 100);
interval_id2 = setInterval(function() {
transmit_game_server_if_changed();
}, 5000);
//if key e is pressed do function split()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 69){
emitSplit();
}
});
//if key r is pressed do function eject()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 82){
emitMassEject();
}
});
function transmit_game_server_if_changed(){
if(last_transmited_game_server != window.agar.ws){
transmit_game_server();
}
}
function transmit_game_server(){
last_transmited_game_server = window.agar.ws;
socket.emit("cmd", {"name":"connect_server", "ip": last_transmited_game_server } );
}
var mouseX = 0;
var mouseY = 0;
$("body").mousemove(function( event ) {
mouseX = event.clientX;
mouseY = event.clientY;
});
window.agar.minScale = -30;
}, 5000);
//EXPOSED CODE BELOW
var allRules = [
{ hostname: ["agar.io"],
scriptUriRe: /^http:\/\/agar\.io\/main_out\.js/,
replace: function (m) {
m.removeNewlines()
m.replace("var:allCells",
/(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
"$1" + "$v=$2;" + "$2$3",
"$v = {}")
m.replace("var:myCells",
/(case 32:)(\w+)(\.push)/,
"$1" + "$v=$2;" + "$2$3",
"$v = []")
m.replace("var:top",
/case 49:[^:]+?(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
m.replace("var:ws",
/new WebSocket\((\w+)[^;]+?;/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("var:topTeams",
/case 50:(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
var dr = "(\\w+)=\\w+\\.getFloat64\\(\\w+,!0\\);\\w+\\+=8;\\n?"
var dd = 7071.067811865476
m.replace("var:dimensions",
RegExp("case 64:"+dr+dr+dr+dr),
"$&" + "$v = [$1,$2,$3,$4],",
"$v = " + JSON.stringify([-dd,-dd,dd,dd]))
var vr = "(\\w+)=\\w+\\.getFloat32\\(\\w+,!0\\);\\w+\\+=4;"
m.save() &&
m.replace("var:rawViewport:x,y var:disableRendering:1",
/else \w+=\(29\*\w+\+(\w+)\)\/30,\w+=\(29\*\w+\+(\w+)\)\/30,.*?;/,
"$&" + "$v0.x=$1; $v0.y=$2; if($v1)return;") &&
m.replace("var:disableRendering:2 hook:skipCellDraw",
/(\w+:function\(\w+\){)(if\(this\.\w+\(\)\){\+\+this\.[\w$]+;)/,
"$1" + "if($v || $H(this))return;" + "$2") &&
m.replace("var:rawViewport:scale",
/Math\.pow\(Math\.min\(64\/\w+,1\),\.4\)/,
"($v.scale=$&)") &&
m.replace("var:rawViewport:x,y,scale",
RegExp("case 17:"+vr+vr+vr),
"$&" + "$v.x=$1; $v.y=$2; $v.scale=$3;") &&
m.reset_("window.agar.rawViewport = {x:0,y:0,scale:1};" +
"window.agar.disableRendering = false;") ||
m.restore()
m.replace("reset",
/new WebSocket\(\w+[^;]+?;/,
"$&" + m.reset)
m.replace("property:scale",
/function \w+\(\w+\){\w+\.preventDefault\(\);[^;]+;1>(\w+)&&\(\1=1\)/,
`;${makeProperty("scale", "$1")};$&`)
m.replace("var:minScale",
/;1>(\w+)&&\(\1=1\)/,
";$v>$1 && ($1=$v)",
"$v = 1")
m.replace("var:region",
/console\.log\("Find "\+(\w+\+\w+)\);/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("cellProperty:isVirus",
/((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\2;)/,
"$1$4.isVirus=$3")
m.replace("var:dommousescroll",
/("DOMMouseScroll",)(\w+),/,
"$1($v=$2),")
m.replace("var:skinF hook:cellSkin",
/(\w+.fill\(\))(;null!=(\w+))/,
"$1;" +
"if($v)$3 = $v(this,$3);" +
"if($h)$3 = $h(this,$3);" +
"$2");
/*m.replace("bigSkin",
/(null!=(\w+)&&\((\w+)\.save\(\),)(\3\.clip\(\),\w+=)(Math\.max\(this\.size,this\.\w+\))/,
"$1" + "$2.big||" + "$4" + "($2.big?2:1)*" + "$5")*/
m.replace("hook:afterCellStroke",
/\((\w+)\.strokeStyle="#000000",\1\.globalAlpha\*=\.1,\1\.stroke\(\)\);\1\.globalAlpha=1;/,
"$&" + "$H(this);")
m.replace("var:showStartupBg",
/\w+\?\(\w\.globalAlpha=\w+,/,
"$v && $&",
"$v = true")
var vAlive = /\((\w+)\[(\w+)\]==this\){\1\.splice\(\2,1\);/.exec(m.text)
var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text)
!vAlive && console.error("Expose: can't find vAlive")
!vEaten && console.error("Expose: can't find vEaten")
if (vAlive && vEaten)
m.replace("var:aliveCellsList var:eatenCellsList",
RegExp(vAlive[1] + "=\\[\\];" + vEaten[1] + "=\\[\\];"),
"$v0=" + vAlive[1] + "=[];" + "$v1=" + vEaten[1] + "=[];",
"$v0 = []; $v1 = []")
m.replace("hook:drawScore",
/(;(\w+)=Math\.max\(\2,(\w+\(\))\);)0!=\2&&/,
"$1($H($3))||0!=$2&&")
m.replace("hook:beforeTransform hook:beforeDraw var:drawScale",
/(\w+)\.save\(\);\1\.translate\((\w+\/2,\w+\/2)\);\1\.scale\((\w+),\3\);\1\.translate\((-\w+,-\w+)\);/,
"$v = $3;$H0($1,$2,$3,$4);" + "$&" + "$H1($1,$2,$3,$4);",
"$v = 1")
m.replace("hook:afterDraw",
/(\w+)\.restore\(\);(\w+)&&\2\.width&&\1\.drawImage/,
"$H();" + "$&")
m.replace("hook:cellColor",
/(\w+=)this\.color;/,
"$1 ($h && $h(this, this.color) || this.color);")
m.replace("var:drawGrid",
/(\w+)\.globalAlpha=(\.2\*\w+);/,
"if(!$v)return;" + "$&",
"$v = true")
m.replace("hook:drawCellMass",
/&&\((\w+\|\|0==\w+\.length&&\(!this\.\w+\|\|this\.\w+\)&&20<this\.size)\)&&/,
"&&( $h ? $h(this,$1) : ($1) )&&")
m.replace("hook:cellMassText",
/(\.\w+)(\(~~\(this\.size\*this\.size\/100\)\))/,
"$1( $h ? $h(this,$2) : $2 )")
m.replace("hook:cellMassTextScale",
/(\.\w+)\((this\.\w+\(\))\)([\s\S]{0,1000})\1\(\2\/2\)/,
"$1($2)$3$1( $h ? $h(this,$2/2) : ($2/2) )")
var template = (key,n) =>
`this\\.${key}=\\w+\\*\\(this\\.(\\w+)-this\\.(\\w+)\\)\\+this\\.\\${n};`
var re = new RegExp(template('x', 2) + template('y', 4) + template('size', 6))
var match = re.exec(m.text)
if (match) {
m.cellProp.nx = match[1]
m.cellProp.ny = match[3]
m.cellProp.nSize = match[5]
} else
console.error("Expose: cellProp:x,y,size search failed!")
}},
]
function makeProperty(name, varname) {
return "'" + name + "' in window.agar || " +
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) { tryReplace(e.target, e) }
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {childList: true})
}
}
// Stage 3: Replace found element using rules
function tryReplace(node, event) {
var scriptLinked = rules.scriptUriRe && rules.scriptUriRe.test(node.src)
var scriptEmbedded = rules.scriptTextRe && rules.scriptTextRe.test(node.textContent)
if (node.tagName != "SCRIPT" || (!scriptLinked && !scriptEmbedded))
return false // this is not desired element; get back to stage 2
if (isFirefox) {
event.preventDefault()
window.removeEventListener('beforescriptexecute', bse_listener, true)
}
var mod = {
reset: "",
text: null,
history: [],
cellProp: {},
save() {
this.history.push({reset:this.reset, text:this.text})
return true
},
restore() {
var state = this.history.pop()
this.reset = state.reset
this.text = state.text
return true
},
reset_(reset) {
this.reset += reset
return true
},
replace(what, from, to, reset) {
var vars = [], hooks = []
what.split(" ").forEach((x) => {
x = x.split(":")
x[0] === "var" && vars.push(x[1])
x[0] === "hook" && hooks.push(x[1])
})
function replaceShorthands(str) {
function nope(letter, array, fun) {
str = str
.split(new RegExp('\\$' + letter + '([0-9]?)'))
.map((v,n) => n%2 ? fun(array[v||0]) : v)
.join("")
}
nope('v', vars, (name) => "window.agar." + name)
nope('h', hooks, (name) => "window.agar.hooks." + name)
nope('H', hooks, (name) =>
"window.agar.hooks." + name + "&&" +
"window.agar.hooks." + name)
return str
}
var newText = this.text.replace(from, replaceShorthands(to))
if(newText === this.text) {
console.error("Expose: `" + what + "` replacement failed!")
return false
} else {
this.text = newText
if (reset)
this.reset += replaceShorthands(reset) + ";"
return true
}
},
removeNewlines() {
this.text = this.text.replace(/([,\/])\n/mg, "$1")
},
get: function() {
var cellProp = JSON.stringify(this.cellProp)
return `window.agar={hooks:{},cellProp:${cellProp}};` +
this.reset + this.text
}
}
if (scriptEmbedded) {
mod.text = node.textContent
rules.replace(mod)
if (isFirefox) {
document.head.removeChild(node)
var script = document.createElement("script")
script.textContent = mod.get()
document.head.appendChild(script)
} else {
node.textContent = mod.get()
}
console.log("Expose: replacement done")
} else {
document.head.removeChild(node)
var request = new XMLHttpRequest()
request.onload = function() {
var script = document.createElement("script")
mod.text = this.responseText
rules.replace(mod)
script.textContent = mod.get()
// `main_out.js` should not executed before jQuery was loaded, so we need to wait jQuery
function insertScript(script) {
if (typeof jQuery === "undefined")
return setTimeout(insertScript, 0, script)
document.head.appendChild(script)
console.log("Expose: replacement done")
}
insertScript(script)
}
request.onerror = function() { console.error("Expose: response was null") }
request.open("get", node.src, true)
request.send()
}
return true
}
Lines 260-267 for easier debugging purposes:
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
Specific line having issues:
return console.error("Expose: this script should run at document-start")
UPDATE:
New issue. Uncaught SyntaxError: Illegal return statement engine.js:282
Lines 281-282 for debugging purposes:
if (!rules)
return console.error("Expose: cant find corresponding rule")
UPDATE 2:
This is my final issue. And this whole thing will be resolved.
It looks like its another return error. But i do not understand how to properly return this part.
Heres the error but its basically the same.
Uncaught SyntaxError: Illegal return statement engine.js:295
Located at line 295
Line 293 to Line 295 for debugging purposes:
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i])){
return
}
here's a fix for the block of code that's causing the error
if (window.top == window.self) {
if (document.readyState !== 'loading') {
// don't return
console.error("Expose: this script should run at document-start")
} else {
// else block for state == 'loading'
The rest of the code is unchanged except for a closing } at the end
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) {
tryReplace(e.target, e)
}
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {
childList: true
})
}
} // added this closing }
}

SetSelectedRange Spread.NET javascript issue

I'm trying to add functionality to Spread.NET control where it will permit a hold shift-click to select a range of cells in ASP.
I'm creating the event onActiveCellChanged to call the selectRange function on execution
var shiftPressed = false;
var newSelect = true;
window.pageLoad = function init() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
if (ss.addEventListener != null) {
ss.addEventListener("ActiveCellChanged", selectRange(), false);
} else if (ss.attachEvent != null) {
ss.attachEvent("ActiveCellChanged", selectRange());
}
else {
FpSpread1.onActiveCellChanged = selectRange;
}
}
Here is the selectRange function.
function selectRange() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
var swap;
if (shiftPressed == true) {
var initRow = document.getElementById('RowCoord').value;
var initCol = document.getElementById('ColCoord').value;
var SecRow = getRow();
var SecCol = getCol();
newSelect = false;
var rCount = Math.abs(SecRow - initRow) + 1;
var cCount = Math.abs(SecCol - initCol) + 1;
if (initRow > SecRow)
initRow = SecRow;
if (initCol > SecCol)
initCol = SecCol;
//alert(initRow + ' ' + initCol);
alert(initRow + ' ' + initCol + ' ' + rCount + ' ' + cCount);
ss.SetSelectedRange(initRow, initCol, rCount, cCount);
}
else {
document.getElementById('RowCoord').value = 0;
document.getElementById('ColCoord').value = 0;
newSelect = true;
}
}
And this is how I'm determining whether shift is being held.
function aKeyDown(event) {
if (event.keyCode == 16) {
shiftPressed = true;
var col = getCol();
var row = getRow();
if (newSelect) {
document.getElementById('RowCoord').value = row;
document.getElementById('ColCoord').value = col;
}
}
}
function aKeyUp(event) {
if (event.keyCode == 16) {
shiftPressed = false;
}
}
function getRow() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
ret = ss.ActiveRow;
if (ret == undefined)
ret = ss.GetActiveRow;
return ret;
}
function getCol() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
ret = ss.ActiveCol;
if (ret == undefined)
ret = ss.GetActiveCol;
return ret;
}
The SetSelectedRange in the select range function will work if my initial cell is a,1. However, if it's any other cell, it'll select the entire row and column.
Here is my <div> tag:
<FarPoint:FpSpread onkeydown="aKeyDown(event)" onkeyup="aKeyUp(event)" ID="FpSpread1"...
In image 1, My initial cell was (a,3) and I held shift and clicked on (b,4)
In image 2, it works. As long as I start at cell (a,1)
I needed to parseInt the row and column values.
function getRow() {
var ss = document.getElementById(spd);
ret = ss.ActiveRow;
if (ret == undefined)
ret = ss.GetActiveRow();
return parseInt(ret);
}
function getCol() {
var ss = document.getElementById(spd);
ret = ss.ActiveCol;
if (ret == undefined)
ret = ss.GetActiveCol();
return parseInt(ret);
}

Categories