Pug (express view engine) nesting with conditionals - express

i'm using pug as my viewengine for express (node js), but im having trouble with some conditionals. I use a grid framework for newsletter designs which works similar to bootstraps grid, meaning i have rows and columns. I need two items per row, which requires to define a new row every two items. I tried it this way:
each elem,index in elements
- var even = index % 2;
if(even)
.row
.column
else
.column
This doenst work as intended, because the else-column is not nested insinde the row column. I could only find the pugjs.org documentation which is a bit poor on this end, so does anyone have experience with this or a link to more documentation? Thanks a lot.

Pug ignores extra indentation, so what you've written is correctly interpreted as:
each elem,index in elements
- var even = index % 2;
if(even)
.row
.column
else
.column
Note that the last .column is truly a sibling of .row.
Instead, try this—
each element, index in elements
if !(index % 2)
.row
.column
if (index + 1 < elements.length)
.column
When index is even (remember it starts at 0) do the following:
Render a row element with one column
If this isn't the last element, add a second column
When index is odd, do nothing (because we already added the second column).
Note that even though it looks like the second column will be rendered as a child of the first column, the contents of an if statement render at the indentation level of the if statement—so they'll be siblings.

Process elements into groups of two.
-
const groupedElements = elements.reduce(function(acc, curr, index) {
let isEven = (index + 1) % 2;
if (isEven) {
acc.push([curr]);
}
else {
acc[acc.length-1].push(curr);
}
return acc;
}, []);
for group in groupedElements
.row
for item in group
.col

Related

Google Sheets API (v4) - `AutoResizeDimensions` not working

I've got a system that generates and automatically maintains lots of spreadsheets on a Drive account.
Whenever I add data to the sheet I run a 'format' method to pass over and make sure everything is ok.
This generally does things like:
set the default font and size across the sheet
set up the heading row
freeze rows
In addition, I have the code below to make sure the first two columns (index 0 and 1) in the sheet are autoresizing to fit their contents. when I run it though, this element doesn't seem to make a difference. The font, column freezes etc all work.
Other notes:
I only want those 2 columns to auto-resize
the amount of rows in a sheet can vary
this job is appended to the end of several in requestList
My code:
requestList.Requests.Add(new Google.Apis.Sheets.v4.Data.Request()
{
AutoResizeDimensions = new AutoResizeDimensionsRequest()
{
Dimensions = new DimensionRange()
{
SheetId = Convert.ToInt32(sheetId),
Dimension = "COLUMNS",
StartIndex = 0,
EndIndex = 1
}
}
});
var updateRequest = sheetService.Spreadsheets.BatchUpdate(requestList, spreadSheetId);
var updateResponse = updateRequest.Execute();
Could the order which I request the 'format' changes be affecting things maybe? Can anyone help?
As written in the documentation,
the start index is inclusive and the end index is exclusive.
So, For the first two columns, it should be
startIndex = 0,
endIndex = 2

How to create a sublist from List<Object> in apache velocity template .vm

I am new to apache velocity, I want to create a subList Object from the List Objects which are coming from some service call in .vm file.
We need to render the list based on some logic in parts, for that we want to create sublist from list.
$table.getBooks() //contains all the Books objects
Below is the sample code which I tried but it did not work.
#set($segregatedList = [])
#set($size = $table.getLineItems().size())
#foreach($index in [0..$size-1])
#set($value = $index + 4)
#set($minimum = $math.min($nItems,$value))
$segregatedList.add($table.getBooks().subList($index,$minimum)))
$index += 4
#end
I executed the code, while rendering $segregatedList is coming as null.
I verified $table.getBooks() contains the Objects as when I am passing this,Objects are getting rendered successfully.
Can someone please tell what I am doing wrong or how can I create a sublist ?
First you are increment index with 4 and can cause an IndexOutOfBoundsException, so need to change until size-5 (and therefore remove math minimum check)
Second you are adding single Element instead of all Elements using addAll
Third your size check if on wrong parameter - should be on relevant $table.getBooks()
And last make sure your list have more than 5 elements
#set($segregatedList = [])
#set($size = $table.getBooks().size())
#foreach($index in [0..$size-5])
#set($value = $index + 4)
$segregatedList.addAll($table.getBooks().subList($index, $value)))
$index += 4
#end

Getting all the cell values from table using table header using Webdriver

Below is the HTML code for the tables:
I need to extract values from table preceding with header as "Opportunities".
Could someone please suggest the best way forward as I can extract values fine if they belong to the same table but I need help when they are in two different table and i need to look for table opportunities and than extract data from the preceding table.
Sure here is my best interpretation of what you need in Java. Any questions and I'll alter my solution to accommodate them. This starts with an index of 0,0 for row and column.
int row = 0, column = 1; //it's 1 to accommodate fogr the first thing you want being a 'th' tag
List<WebElement> tableRows = driver.findElements(By.className("dataRow"));//this gets all elements on your page with a class of dataRow (which are your tr's)
for(WebElement singleRow: tableRows) //this for loop increments each of these tr's
{
System.out.println(singleRow.findElement(By.xpath("th[1]/a[1]")).getText()); //I'll have to use an xpath here because I don't have time to play around with other solutions but it'll work
System.out.println("Row: " + row + ", Column: " + column);
List<WebElement> rowTDs = singleRow.findElements(By.tagName("td"));//this gets every td in the current tr and puts it into a list
for(WebElement singleTD: rowTDs) //this increments through that list of td's
{
System.out.println(singleTD.getText()); //this gives you back the text contained in that cell
System.out.println("Row: " + row + ", Column: " + column);
column++; //increment the column counter
}
column=1; //reset the column
row++; //increment the row counter
}
Edit: It seems that given that element of the request "Saykiro" has almost the right of it and you can replace in my solution tableRows = with this, there's probably a more succinct way to get the second table but this is what comes to me:
WebElement table1 = driver.findElemen(By.id("001Z000000vrLQe_RelatedOpportunityList_title"));
WebElement table2 = table1.findElement(By.xpath("../../../../following-sibling::table"))
List<WebElement> tableRows = table2.findElements(By.className("dataRow"));
For your case:
//*[table/tbody/tr/td/h3[text()='Opportunities']]/table[2]//td[#class=' dataCell ']
For C# (getting list of values in cells):
var values = driver.FindElements(By.XPath("//*[table/tbody/tr/td/h3[text()='Opportunities']]/table[2]//td[#class=' dataCell ']")).Select(a=>a.Text);
You should describe outer part of html, so we can build xpath better.

Disable or enable edit for selective cell in dojox data grid

How to disable or enable edit for selective cell in dojox data grid i.e
Imagine I have two columns (A, B) in a data grid. I want column value of B to be editable based on the value of column A. I have seen one solution in stack overflow which was specific to a DOJO version. I would like to know if there are APIs by which we can achieve above objective.
My preferred method is to override the
canEdit: function(inCell, inRowIndex)
method of the DataGrid. From that, you can get the item:
this.getItem(inRowIndex)
then work out if it should be editable or not, and return true/false.
This does override the editable flag on the column though, so you'll need to do something with that if needed.
There is no API as such. I also had similar requirement recently and here is how I implemented it:
1) Initially the column B is editable because I made it so in the Fields section of grid
2) Use onRowClick to capture the rendering of rows. Something like this should do
dojo.connect(grid, "onRowClick", grid, function(evt){
var idx = evt.rowIndex,
item = this.getItem(idx);
// get a value out of the item
msname = this.store.getValue(item, "msname");
if(msname != null &U& (trim(msname) == trim(offsetName))) {
dojox.grid.cells._Base.prototype.format(idx, item);
}
});
The following method then disallows inline editing of required column. We are passing row index and column index to this following function:
dojox.grid.cells._Base.prototype.format = function(inRowIndex, inItem){
var f, i=grid.edit.info, d=this.get ? this.get(inRowIndex, inItem) : (this.value || this.defaultValue);
d = (d && d.replace && grid.escapeHTMLInData) ? d.replace(/&/g, '&').replace(/</g, '<') : d;
//Check inRowIndex and inItem to determine whether to be editable for this row here.
if(this.editable && (this.alwaysEditing || (i.rowIndex==inRowIndex && i.cell==this))){
return this.formatEditing(d, inRowIndex);
}else{
return this._defaultFormat(d, [d, inRowIndex, this]);
}
}
Hope that helps. Probably you can add a jsfiddle and we can try fixing it.

Specify local Dynamic in Grid

I would like to update specific parts of a Grid dynamically in different ways. Consider the following toy example: I have two rows: one must be updated one-by-one (a, b, c), as these symbols depend on different triggers; the second row depends on one single trigger (show) that allows displaying/hiding some data.
Now I know that I can wrap the whole Grid structure into Dynamic, and even specify which symbols to track, thus this example does what I want:
Checkbox[Dynamic[show]]
test = {0, 0};
Dynamic[Grid[{{Dynamic#a, Dynamic#b, Dynamic#c},
If[show, Prepend[test, "test:"], {}]}, Frame -> All],
TrackedSymbols :> {show}]
Though for certain reasons I would like to have a locally specified Dynamic, that is only applied to the second row of the Grid.
For those who are wondering what ungodly situation would it be, just imagine the followings: show is used in any of a, b or c, and these I do NOT want to update when show is changing, their changes depend on other triggers. Why not remove then show from the symbols of the first row? Imagine, I can't, as show is present in a function that is used in a, b or c, and this function I cannot access easily.
Of course wrapping the first argument of If into Dynamic won't help here, as the Grid itself or any of its cells won't become dynamic:
Grid[{
{Dynamic#a, Dynamic#b, Dynamic#c},
If[Dynamic#show, Prepend[test, "test:"], {}]
}, Frame -> All]
Furthermore, wrapping a row into Dynamic makes the given row invalid, as it does not have head List anymore:
Grid[{
{Dynamic#a, Dynamic#b, Dynamic#c},
Dynamic#If[show, Prepend[test, "test:"], {}]
}, Frame -> All]
Mapping Dynamic over the row does not work either because show is not updated dynamically:
Grid[{
{Dynamic#a, Dynamic#b, Dynamic#c},
Dynamic /# If[show, Prepend[test, "test:"], {}]
}, Frame -> All]
Also, wrapping Dynamic[If[...]] around list members work, but now I have to evaluate If 3 times instead of just 1.
Grid[{
{Dynamic#a, Dynamic#b, Dynamic#c},
Dynamic[If[show, #, ""]] & /# Prepend[test, "test:"]
}, Frame -> All]
Would like to know if there is any solution to overcome this particular problem by locally applying a Dynamic wrapper on a row.
Here is a solution using the Experimental ValueFunction
show = True;
test = {0, 0};
Checkbox[Dynamic[show]]
Now write your own little Dynamic update function on the side
Needs["Experimental`"];
row = {};
updateRow[x_, v_] := row = If[v, Prepend[test, "test:"], {}];
ValueFunction[show] = updateRow;
Now make the Grid, and now can use Dynamic on EACH row, not around the whole Grid, which is what you wanted:
Grid[{
{Dynamic#a, Dynamic#b, Dynamic#c},
{Dynamic#row}
},
Frame -> All
]
ps. I just read a post here by telefunkenvf14 that mentions this package and this function, which I did not know about, and when I saw this function, I remembered this question, and I thought it should be possible to use that function to solve this problem.
ps. I need to work more on placing the grid row correctly....
update(1)
I can't figure how to splice the final row over the columns in the grid. Which is strange, as it has List head, yet it won't go across all the columns. It will only go in the first cell. Tried Sequence, SpanFromLeft, and such, but no luck. May be someone can figure this part out.
Here is my current trial:
Needs["Experimental`"];
row = {};
updateRow[x_, v_] := row = If[v, {"test:", 0, 0}, {}];
ValueFunction[show] = updateRow;
show = False;
Checkbox[Dynamic[show]]
f = Grid[{
{Dynamic#a, Dynamic#b, Dynamic#c},
List#Dynamic[row]
},
Frame -> All
]
It seems it should be doable. I do not see what is the problem now...
update(2)
As a temporary solution, I split the second row by force before hand. This made it possible to do what I want. Not sure if this meets the OP specifications or not (my guess is that it does not), but here it is:
Needs["Experimental`"];
ra = 0;
rb = 0;
rc = 0;
updateRow[x_, v_] :=
row = If[v, ra = "test:"; rb = 0; rc = 0, ra = ""; rb = ""; rc = ""]
ValueFunction[show] = updateRow;
show = False;
Checkbox[Dynamic[show]]
f = Grid[{
{Dynamic#a, Dynamic#b, Dynamic#c},
{Dynamic#ra, Dynamic#rb, Dynamic#rc}
},
Frame -> All]
This is actually a comment on #Nasser's solution and suggested fix to avoid manual splitting of the second row, but because of space limitations in the comment area, I post it as answer. Will be happy to delete it as soon as Nasser confirms that it works and incorporates it into his answer.
The clue to a solution is found in the Possible Issues section of Item in the documentation:
If Item is not the top-most item in the child of a function that supports Item, it will not work.
I use this to modify #Nasser's solution in the following way. First, I need to change the definition of row so that for both values of show the length of row is the same.
Needs["Experimental`"];
row = {"", "", ""};
updateRow[x_, v_] := row = If[v, Prepend[test, "test:"], {"", "", ""}];
Experimental`ValueFunction[show] = updateRow;
The second change needed is to wrap each element of Dynamic#row with Item:
Grid[{{Dynamic#a, Dynamic#b, Dynamic#c},
{Item[Dynamic#row[[1]]], Item[Dynamic#row[[2]]],
Item[Dynamic#row[[3]]]}}, Frame -> All]
Edit: Item wrapper is not really needed; it works just as well without it:
Grid[{{Dynamic#a, Dynamic#b, Dynamic#c},
{Dynamic#row[[1]], Dynamic#row[[2]],
Dynamic#row[[3]]}}, Frame -> All]