In Pug, how to use a variable outside (set for global use) the each loop it is created in? - loops

Below, I'm trying to get the personRef variable inside (locally set scope) the pug each loop of person in persons to come out. That way on the following line PersObj which I need for each object loop it's a part of can use the personRef variable from the loop right above. Basically, I need the local scope in the loop to be set globally outside the loop.
each object in objects
- var objNum = objects.indexOf(vehicle)+1
- var personRef=person.object_ref
each person in persons
- var personNum = persons.indexOf(driver)+1
if (some condition) && (object.person_ref == objNum)
- var personRef=object.person_ref
- break
else if (condition)
- var personRef= personNum
else if (condition)
- continue
PersObj(id = "O"+objNum, PersonRef = "P"+personRef)

its hard to understand what exact behavoir you want to achieve but i will try.
"- var personRef = something" defines a variable. you only need this once in your code. if you define it outside of a loop, you can also use it inside. if you have "- var personRef = something" again inside the loop, you "overwrite" it with a variable that can only be used within the loops scope. you can always reassign a variables value like this: "personRef = somethingElse" with out using the "- var".
so it should probably look smth like this:
each object in objects
- var objNum = objects.indexOf(vehicle)+1
- var personRef=person.object_ref // define the variable here
each person in persons
- var personNum = persons.indexOf(driver)+1
if (some condition) && (object.person_ref == objNum)
- personRef=object.person_ref // here you dont need var, because you only reassign a value
- break
else if (condition)
- personRef= personNum // here as well
else if (condition)
- continue
PersObj(id = "O"+objNum, PersonRef = "P"+personRef)
besides that, i cant really tell what the code is supposed to do, can you please elaborate what that code is supposed to do. please also explain:
what is "objects"
what is "persons"
what is "vehicle"
what is "driver"

Related

In a form, I need to populate the contents of same spreadsheet column like 50 times. Is there a way to script this logic with fewer iterations

I'm working on a form where I need to pull the contents of a spreadsheet column like 50 times, to try to input multiple items from a list. I see that I can do this by defining a few variables and redoing a small piece of Script again and again. I want to see if anyone can help me overcome this lengthy script to make it smaller with fewer iterations. Thanks.
function updateForm(){
// call the form and connect to the drop-down items
var Form_SQ = FormApp.openById("FORM ID");
var SQ_IT01_List = Form_SQ.getItemById("ITEM 01").asListItem();
var SQ_IT02_List = Form_SQ.getItemById("ITEM 02").asListItem();
//Similarly defining upto 50 dropdown lists.
var SS01 = SpreadsheetApp.getActive();
var SQ_IT01_Names = SS01.getSheetByName("Sheet2");
var SQ_IT02_Names = SS01.getSheetByName("Sheet2");
//Similarly defining upto 50 names lists.
// Item_01 Part Number Dropdown
var SQ_IT01_Values = SQ_IT01_Names.getRange(2, 1, SQ_IT01_Names.getMaxRows() - 1).getValues();
var SQ_IT01_Items = [];
for(var i = 0; i < SQ_IT01_Values.length; i++)
if(SQ_IT01_Values[i][0] != "")
SQ_IT01_Items[i] = SQ_IT01_Values[i][0];
SQ_IT01_List.setChoiceValues(SQ_IT01_Items);
// Item_02 Part Number Dropdown
var SQ_IT02_Values = SQ_IT01_Names.getRange(2, 1, SQ_IT02_Names.getMaxRows() - 1).getValues();
var SQ_IT02_Items = [];
for(var i = 0; i < SQ_IT02_Values.length; i++)
if(SQ_IT02_Values[i][0] != "")
SQ_IT02_Items[i] = SQ_IT02_Values[i][0];
SQ_IT02_List.setChoiceValues(SQ_IT02_Items);
//Similarly defining upto 50 lookup lists.
}
Problem
Reusing code and making use of loops. Scripting is all about efficiency (see DRY principle): make as little assignments and same-functionality coding as possible - use loops, move reusable code snippets to functions that can be called on demand, etc.
Solution
This sample makes several assumptions:
SQ_IT01_Names is different for each item (in your sample it always is Sheet2 - if this is the case, you don't have to reassign it 50 times, one variable assignment will do just fine).
You intended to do something when a value is an empty string (the sample just filters them out). As you use the [index] notation, those values in the resulting Array will be undefined (and that's not something one would want in an Array of choice values).
All items are choice items (if you need id filtering, the sample is easily expanded).
function updateForm() {
var form = FormApp.openById("FORM ID");
//access every item;
var items = form.getItems();
var ss = SpreadsheetApp.getActive();
//loop over items;
items.forEach(function(item,i){
var namesSheet = ss.getSheetByName('Sheet'+i); //assuming this is diff each time;
var namesRange = namesSheet.getRange(2,1,namesSheet.getLastRow());
var namesValues = namesRange.getValues();
//map values to first column;
namesValues = namesValues.map(function(value){
return value[0];
});
//filter out undefined (undefined and false functional equivalence);
namesValues = namesValues.filter(function(value){
return value;
});
item.asListItem().setChoiceValues(namesValues);
});
}
Notes
Please, use closures {} with loops and if statements, this way you'll be able to keep track of which statements are enclosed in it and save yourself debugging time when looping / conditioning multiple statements.
Since you only need rows that have data in them, use the getLastRow() method instead of the getMaxRows()-1 calc you have to perform in your script.
Reference
forEach() method reference;
filter() method reference;
map() method reference;
getLastRow() method reference;

Simple swift array append not working

I know this is going to be super elementary, but I have this piece of code:
var labels: [String]?
func initVC(image: Images){
self.image = image
let tempLabels = image.label?.allObjects as! [Labels]
for i in 0..<tempLabels.count{
labels?.append(tempLabels[i].label!)
}
}
labels is in the public scope, so the function should have access to it, but when the loop runs through, labels is still nil with no elements.
When I po during debugging, tempLabels is as I expect it to be with 2 string elements.
I'm pretty sure this is a very simple problem, but I guess I'm just out of it right now.
Labels has never been initialised. Change
var labels:[String]?
to
var labels:[String] = []
You are declaring the labels variable but never allowing it to store information. This means that it does not necessarily exist, since it is not initialized, and therefore cannot be used.
For it to be useable, you must initialize it
var labels:[String] = []
Yep, it was super simple.
Changed
var labels: [String]?
To
var labels = [String]()

Does AngularJS have a function like eval?

Does AngularJS have any function or method similar to eval?
I need to get the value of a previously-defined variable, e.g.:
data.mess_5 = "Hello"
c = 5
x = eval( "data.mess_" + c )
Angularjs is javascript, so you can use eval, assuming your var is on the global scope. However, in this particular case (and most other cases), eval is the wrong tool for the job.
data.mess_5 = "Hello"
c = 5
x = data['mess_' + c]
Check the $parse function (taken from Setting dynamic scope variables in AngularJs - scope.<some_string>)
var the_string = 'life.meaning';
// Get the model
var model = $parse(the_string);
// Assigns a value to it
model.assign($scope, 42);
// Apply it to the scope
$scope.$apply();
console.log($scope.life.meaning); // logs 42

Trouble finding the correct syntax creating vars in objects

Up until now I have been creating var inside the classes I made. e.g.
var backpack:Array = new Array("food", "water");
I want to create objects dynamically now like:
player = {};
player.backpack = ("food", "water"); // not the right syntax
OR
player = {backpack:Array = new Array("food", "water")} // not right either.
Any help? Thanks in advance. I can do this with simple vars like int, but can't find the answer to arrays.
ActionScript's generic object properties don't have any variable type associated with them. You assign them one of the following ways.
Example 1
player = {backpack: new Array("food", "water")};
Example 2
player.backpack = new Array("food", "water");
Example 3
player["backpack"] = new Array("food", "water");
You can use square brackets to define literal arrays. Not only is it shorter, but it's also faster (see this post).
The correct syntax for your two examples are
player = {};
player.backpack = ["food", "water"];
and
player = {backpack: ["food", "water"]};
Also, if you find it easier, you can use it in the first line of code you wrote.
var backpack:Array = ["food", "water"];

Lua & implicit global state

I'm integrating Lua into my project at the moment, and I'm facing a small design problem on the way. Currently, if I want to get information from my host application into Lua scripts, I call a function that I registered in C, in this fashion:
-- Inside lua
local state = host.get_state()
-- Do something with "state"
Now the problem with that is: the state can obviously change, and the "state" variable will then be outdated and most likely invalid. So far I lived with this because the global state isn't needed too often. It's more problematic in the following scenario:
local user = host.get_user('id')
host.set_user_flags(user, 'abc')
-- internally "user" is now updated, but to get the accurate information in Lua, I
-- will have to explicitly redo "user = host.get_user('id')" for every operation
-- that accesses this table
I have read a bit about references and I think they can help me with this, but I didn't really understand it.
Isn't there some way to just throw around pointers like I can do it in C?
Any link you use inside the function won't change the var outside of it. You should use smthg like this:
local count
function MyFunc()
count = 1
end
There is 'local' isn't necessarily.
As alternative I can suggest you to use non-safety method:
count = 0
function MyFunc(v) --we will throw varname as a string inside
_G[v] = 1 -- _G is a global environment
end
MyFunc('count')
print(count)
I found out that tables are passed as references and I'm able to modify them from inside the function like this:
static int dostuff(lua_State *L)
{
lua_pushstring(L, "b");
lua_pushnumber(L, 23);
lua_settable(L, 1);
return 0;
}
/* lua_register(L, "dostuff", &dostuff); */
And inside Lua:
t = { a = 'a', b = 2 }
print(t.a, t.b)
dostuff(t)
print(t.a, t.b)
Will result in:
a 2
a 23

Resources