Passed value to function becomes undefined [duplicate] - javascript

This question already has answers here:
Get an error when I call object's properties in Array
(4 answers)
Closed 3 years ago.
I'm trying to write a script to disable layers in photoshop. So far the first part (first function) works, and it just grabs all the red layers and puts them in an array. Then I call the second function which takes one by one name from the array and passes it to the disabler (showBounds function). However, I'm looking at the input the showBounds receives ("name") and suddenly it stars saying it's getting "undefined". How can this be? what is happening?
var doc = app.activeDocument;
var theLayers = [];
function fillLayerArray(){
// get number of layers;
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var applicationDesc = executeActionGet(ref);
var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
//var theOthers = new Array;
for (var m = 0; m <= theNumber; m++) {
var ref = new ActionReference();
ref.putIndex( charIDToTypeID( "Lyr " ), m);
var layerDesc = executeActionGet(ref);
var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));
var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theColor = layerDesc.getEnumerationValue(stringIDToTypeID("color"));
globColor = theColor;
if (typeIDToStringID(theColor) == "red" && layerSet != "layerSectionEnd" ) {
theLayers.push(theName);
}
};
hideLayers(theNumber);
//showBounds(doc.layerSets);
}
function hideLayers(theNumber){
for (var i = 0; i <= theLayers.length; i++) {
//app.activeDocument.activeLayer.visible = false;
currentLayerName = theLayers[i];
//alert(currentLayerName)
alert(currentLayerName);
showBounds(doc.layerSets, currentLayerName);
}
}
function showBounds(layerNode, name) {
for (var i=0; i<layerNode.length; i++) {
showBounds(layerNode[i].layerSets);
for(var layerIndex=0; layerIndex < layerNode[i].artLayers.length; layerIndex++) {
var layer=layerNode[i].artLayers[layerIndex];
alert(layer.name + name)
try{
if (layer.name == name) {
layer.visible = 0;
}
}catch(e){
}
}
}
}
fillLayerArray();

You have
i <= theLayers.length
Should be
i < theLayers.length
In hideLayers.
(Also in m <= theNumber .... remember arrays are indexed starting from zero in JS)

Related

Backpropagation in an Tensorflow.js Neural Network

When I have been attempting to implement this function tf.train.stg(learningRate).minimize(loss)into my code in order to conduct back-propagation. I have been getting multiple errors such The f passed in variableGrads(f) must be a function. How would I implement the function above into the code bellow successfully? and Why does this error even occur?
Neural Network:
var X = tf.tensor([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
var Y = tf.tensor([[0,0,0],[0,0,0], [1,1,1]])
var m = X.shape[0]
var a0 = tf.zeros([1,3])
var y_hat = tf.zeros([1,3])
var parameters = {
"Wax": tf.randomUniform([1,3]),
"Waa": tf.randomUniform([3,3]),
"ba": tf.zeros([1,3]),
"Wya": tf.randomUniform([3,3]),
"by": tf.zeros([1,3])
}
function RNN_cell_Foward(xt, a_prev, parameters){
var Wax = parameters["Wax"]
var Waa = parameters["Waa"]
var ba = parameters["ba"]
var a_next = tf.sigmoid(tf.add(tf.add(tf.matMul(xt, Wax), tf.matMul(a_prev , Waa)),ba))
return a_next
}
function RNN_FowardProp(X, a0, parameters){
var T_x = X.shape[0]
var a_next = a0
var i = 1
var Wya = parameters["Wya"]
var by = parameters["by"]
var l = 1
for(; i <= T_x; i++){
var X_i = X.slice([i-1,0],[1,-1])
for(; l <= X.shape[1]; l++){
var xt = X_i.slice([0,l-1],[1,1])
var a_next = RNN_cell_Foward(xt, a_next, parameters)
}
var y_pred = tf.sigmoid((tf.add(tf.matMul(a_next, Wya), by)))
l = 1
if (i == 1){
var y_pred1 = y_pred
} else if (i == 2) {
var y_pred2 = y_pred
} else if (i == 3) {
var y_pred3 = y_pred
}
}
var y_predx = tf.concat([y_pred1, y_pred2, y_pred3])
return y_predx
}
const learningRate = 0.01;
var optimizer = tf.train.sgd(learningRate);
var model = RNN_FowardProp(X, a0, parameters)
var loss = tf.losses.meanSquaredError(Y, model)
for (let f = 0; f < 10; f++) {
optimizer.minimize(loss)
}
This is a neural network for sentiment classification which has a many to one structure.
The error says it all:
The f passed in variableGrads(f) must be a function
optimizer.minimize is expecting a function as parameter and not a tensor. Since the code is trying to minimize the meanSquaredError, the argument of minimize can be a function that computes the meanSquaredError between the predicted value and the expected one.
const loss = (pred, label) => pred.sub(label).square().mean();
for (let f = 0; f < 10; f++) {
optimizer.minimize(() => tf.losses.meanSquaredError(Y, model))
}
Does it solve the issue, not completely yet ? The error will change for something like:
variableGrads() expects at least one of the input variables to be trainable
What does it mean ? When the optimizer is used, it expects the function passed as argument to contains variables whose values will be updated to minimize the function output.
Here is the changes to be made:
var Y = tf.tensor([[0,0,0],[0,0,0], [1,1,1]]).variable() // a variable instead
// var loss = tf.losses.meanSquaredError(Y, model)
// computed below in the minimize function
const learningRate = 0.01;
var optimizer = tf.train.sgd(learningRate);
var model = RNN_FowardProp(X, a0, parameters);
const loss = (pred, label) => pred.sub(label).square().mean();
for (let f = 0; f < 10; f++) {
optimizer.minimize(() => tf.losses.meanSquaredError(Y, model))
}

Console.log gives correct output but when accessing set value it gives wrong output

Called Function:
this.findVerticalPossibleScoring = function(){
var possibilitySet = [];
for (var j = 0; j < 9;j++ ) {
for (var i = 0; i < 7; ){
var tempTile = this._tiles[i][j];
if(this.gameTilesValue[i][j]!=-1){
var tileTagValue = this.gameTilesValue[i][j];
if(this.gameTilesValue[i+1][j]==tileTagValue && this.gameTilesValue[i+2][j]==tileTagValue){
setElement = [];
do{
var tempPoint = this.makeArray(i,j);
setElement.push(tempPoint);
console.log(" verical i:"+i+" j:"+j);
i=i+1;
}while(i<9&&this.gameTilesValue[i][j]==tileTagValue);
possibilitySet.push(setElement);
continue;
}
}
i = i+1;
}
}
return possibilitySet;
};
this.makeArray = function (a,b){
console.log("element i:"+a+" j:"+b);
var arrayTemp = [];
arrayTemp.push(a);
arrayTemp.push(b);
return arrayTemp;
};
Calling function part:
if(scoringPossible == true){
//blast the tiles and add new tiles;
var verticalPossibleScoring = this.findVerticalPossibleScoring();
toBeDeletedTiles = [];
for(var i=0;i<verticalPossibleScoring.length;i++){
var tempSet = verticalPossibleScoring[i];
for(var j = 0;j<tempSet.length;j++){
var tempSetEntry = tempSet[i];
console.log("TILE i:"+tempSetEntry[0]+" j:"+tempSetEntry[1]);
}
}
}
I have added called function as well as calling function if loop as calling function is too big. I know this is infamous javascript loop issue. I am using gc-devkit game engine which is new and I new to it. I had solved the same issue for UIImage in it by creating custom class, but here I don't require custom array for it. Can any one guide me through this issue. Thanks in advance.
You use j as your loop variable when iterating over tempSet but then use i when getting elements from tempSet. Maybe just change
var tempSetEntry = tempSet[i];
to
var tempSetEntry = tempSet[j];

Cannot read properties of an object

I have spent many hours on this irritating problem in my code. I define a class to hold several properties. I then populate those properties into a 2d array. From there, I then attempt to modify random elements in the 2d array. I keep getting the message
"Cannot read property of 'attribute' of undefined"
where attribute is any one of the three attributes in my object. Here is my code:
var table = new Array();
var adjacencyList = new Array();
var cell = function (prop) {
var atrbs = {
x: prop.x,
y: prop.y,
isVisited: prop.isVisited
}
return atrbs;
};
var createTable = function(size){
for(var row = 0; row < size; row++){
table[row] = new Array();
for(var column = 0; column < size; column++){
table[row][column] = new cell({x: row, y: column, isVisited: false});
}
}
};
function print(){
for(var row = 0; row < table.length; row++){
for(var column = 0; column < table[row].length; column++){
console.log(table[row][column]);
}
}
};
var randomizeMaze = function(){
var randomX = Math.floor((Math.random() * table.length));
var randomY = Math.floor((Math.random() * table.length));
var currentCell = table[randomX][randomY];
currentCell.isVisited = true;
adjacencyList.push(currentCell);
while( adjacencyList.length > 0 ) {
currentCell.isVisited = true;
var adjacentNodes = getAdjacentNodes(currentCell);
//randomly select a node to add to path
var nextInPath = adjacentNodes[Math.floor((Math.random() * adjacentNodes.length))];
//add to path to not visit it again
adjacencyList.push.apply(adjacencyList, adjacentNodes);
var removeNode = adjacencyList.indexOf(currentCell);
adjacencyList.splice(removeNode, 1);
//reset currentCell to random cell from resized list
currentCell = adjacencyList[Math.floor((Math.random() * adjacencyList.lenth))];
}
};
function getAdjacentNodes(pCell){
var adjacentNodes = new Array();
//check left
if(pCell.x - 1 >= 0){
var node = table[pCell.x-1][pCell.y];
adjacentNodes.push(node);
adjacencyList.push(node);
}
//check right
if(pCell.x + 1 < table.length){
var node = table[pCell.x+1][pCell.y];
adjacentNodes.push(node);
adjacencyList.push(node);
}
//check top
if(pCell.y - 1 >= 0){
var node = table[pCell.x][pCell.y - 1];
adjacentNodes.push(node);
adjacencyList.push(node);
}
//check bottom
if(pCell.y + 1 < table.length){
var node = table[pCell.x][pCell.y + 1];
adjacentNodes.push(node);
adjacencyList.push(node);
}
return adjacentNodes;
};
createTable(3);
//print();
randomizeMaze();
Whenever I try and access/change any property inside of a cell, namely in the functions 'randomeMaze' and 'getAdjacentNodes', it will throw the error I mentioned. I can print the objects to console, I see the objects as being populated when I debug. Maybe I'm missing something and am going crazy.
Any help would be greatly appreciated.

Multi-dimensional Javascript open array

I have difficulty with assigning and retrieving the values of elements in the open array, the array size and dimensions are not fixed so its due to expand or shrink during the iteration. I declare the array as var NODES[[]]; trying to assign, retrieving values and obtaining the length of any dimension in array results wrong values. Especially with the var le = NODES[0].length ; code I 'd expect to see the total length of first dimension.
var NODES =[[]]
scene = editor.scene;
scene.traverse( function(e) {
if ( (e instanceof THREE.Line) && (e.name = 'main line' ) )
{
for (i=0; i<e.geometry.vertices.length; i++){
var x = e.position.x+ e.geometry.vertices[i].x
var y = e.position.y+ e.geometry.vertices[i].y
var z = e.position.z+ e.geometry.vertices[i].z
NODES[node_cnt,0] = x;
NODES[node_cnt,1] = y;
NODES[node_cnt,2] = z;
node_cnt++;
}
cnt++;
};
var le = NODES[0].length ;
EXPECTED RESULT
NODES[0][0] = 10; NODES[0][1] = 20; NODES[0][3] = 30;
NODES[1][0] = 40; NODES[1][1] = 50; NODES[1][3] = 60;
NODES[2][0] = 70; NODES[2][1] = 80; NODES[2][3] = 90;
with `var le = NODES[0].length ;` I expect to see 3 because I'm requesting the length of 1st dimension
This is the javascript interpretation of multi dimensional array, NODES is an array which contains actually 3 array, every array contained in NODES contain a string:
var NODES = [[],[],[]];
for (var i = 0; i < 10 ; i++) {
NODES[0].push(i + 'x');
NODES[1].push(i + 'y');
NODES[2].push(i + 'z');
}
console.log(NODES[0].lenght);
If every contained array should contain one another array the sintax to do this should be:
NODES[0].push([i + 'x']);
Sorry, I'm not understand clearly what mean node_cnt and cnt, but I think you should do something like this:
var NODES =[[],[],[]]
scene = editor.scene;
scene.traverse( function(e) {
if ( (e instanceof THREE.Line) && (e.name = 'main line' ) )
{
for (i=0; i<e.geometry.vertices.length; i++){
var x = e.position.x+ e.geometry.vertices[i].x
var y = e.position.y+ e.geometry.vertices[i].y
var z = e.position.z+ e.geometry.vertices[i].z
NODES[0].push(x);
NODES[1].push(y);
NODES[2].push(z);
node_cnt++;
}
cnt++;
};
var le = NODES[0].length ;

Find min and max value in csv file

Looking to extend my javascript object, I want to find the minium and maximum of a multicolumn csvfile. I have looked up solutions but I cannot really grasp the right way. I found a solution here: Min and max in multidimensional array but I do not get an output.
My code that I have for now is here:
function import(filename)
{
var f = new File(filename);
var csv = [];
var x = 0;
if (f.open) {
var str = f.readline(); //Skips first line.
while (f.position < f.eof) {
var str = f.readline();
csv.push(str);
}
f.close();
} else {
error("couldn't find the file ("+ filename +")\n");
}
for (var i=(csv.length-1); i>=0; i--) {
var str = csv.join("\n");
var a = csv[i].split(","); // convert strings to array (elements are delimited by a coma)
var date = Date.parse(a[0]);
var newdate = parseFloat(date);
var open = parseFloat(a[1]);
var high = parseFloat(a[2]);
var low = parseFloat(a[3]);
var close = parseFloat(a[4]);
var volume = parseFloat(a[5]);
var volume1000 = volume /= 1000;
var adjusted_close = parseFloat(a[6]);
outlet(0, x++, newdate,open,high,low,close,volume1000,adjusted_close); // store in the coll
}
}
Edit
What if, instead of an array of arrays, you use an array of objects? This assumes you're using underscore.
var outlet=[];
var outletkeys=['newdate','open','high','low','close','volume','volume1000','adjusted_close'];
for (var i=(csv.length-1);i>0; i--) {
var a = csv[i].split(",");
var date = Date.parse(a[0]);
var volume = parseFloat(a[5],10);
outlet.push( _.object(outletkeys, [parseFloat(date,10) , parseFloat(a[1],10) , parseFloat(a[2],10) , parseFloat(a[3],10) , parseFloat(a[4],10) , parseFloat(a[5],10) , volume /= 1000 , parseFloat(a[6],10) ]) );
}
Then the array of the column 'open' would be
_.pluck(outlet,'open');
And the minimum it
_.min(_.pluck(outlet,'open'));
Edit2
Let's forget about underscore for now. I believe you need to get the maximum value on the second column, which is what you put in your open variable.
¿Would it help if you could have that value right after the for loop? For example
var maxopen=0;
for (var i=(csv.length-1); i>=0; i--) {
var a = csv[i].split(",");
var date = Date.parse(a[0]);
var newdate = parseFloat(date);
var open = parseFloat(a[1]);
maxopen=(open>maxopen)? open : maxopen; // open overwrites the max if it greater
...
...
outlet(0, x++, newdate,open,high,low,close,volume1000,adjusted_close);
}
console.log('Maximum of open is',maxopen);

Categories