Detecting first and last item inside a Groovy each{} closure - html

I am using Groovy's handy MarkupBuilder to build an HTML page from various source data.
One thing I am struggling to do nicely is build an HTML table and apply different style classes to the first and last rows. This is probably best illustrated with an example...
table() {
thead() {
tr(){
th('class':'l name', 'name')
th('class':'type', 'type')
th('description')
}
}
tbody() {
// Add a row to the table for each item in myList
myList.each {
tr('class' : '????????') {
td('class':'l name', it.name)
td('class':'type', it.type)
td(it.description)
}
}
}
}
In the <tbody> section, I would like to set the class of the <tr> element to be something different depending whether the current item in myList is the first or the last item.
Is there a nice Groovy-ified way to do this without resorting to something manual to check item indexes against the list size using something like eachWithIndex{}?

You could use
if(it == myList.first()) {
// First element
}
if(it == myList.last()) {
// Last element
}

The answer provided by sbglasius may lead to incorrect result like when the list contains redundants elements so an element from inside the list may equals the last one.
I'm not sure if sbglasius could use is() instead of == but a correct answer could be :
myList.eachWithIndex{ elt, i ->
if(i == 0) {
// First element
}
if(i == myList.size()-1) {
// Last element
}
}

if (it.after.value != null) {
......
}
Works for maps

Related

Display a value in HTML using MVC

I have a list held by Session's variable. Suppose: Session["SOF"].
Within this list, there are several items. Suppose each item is an integer. Let's say I want to find the item which has the value 9 and then display the item's value in HTML (this thing is clearly stupid but it is just example).
Here is what I tried in my HTML code in order to display the number:
#(List<int>(Session["SOF"]).FirstOrDefault(x => x.value == 9).ToString());
obviously it didn't work. So how can I do it?
I would use foreach in this case
Try this:
#foreach(var item in Session["SOF"])
{
if(item == 9)
{
<span>#item.ToString()</span>
}
}
Maybe casting to a List<int> will be needed for Session["SOF"], but give it a try.

Qtableview, add widgets between rows

I have a QTableview (multiple columns, sorting) and would like to add a button that shows additional data below the current row. For the rendering of this additional data I would like to use another widget, that fills up a variable height and spans all the rows.
While I know that I can create delegates for cells, I was wondering if this is possible for rows or whether that would mean that I would have to inherit from a tableview and modify its paint method, which seems to be lot of work for a novice like me.
QVariant YourTableModel::data(const QModelIndex & index, int32_t role) const
{
if (!index.isValid()) {
return QVariant();
}
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
switch (index.column())
{
case YOUR_COL:
double theDouble = getDoubleFromModelSomewhere();
return QString::number(theDouble, 'f', 3); // Format shows 3 decimals
}
}
return QVariant();
}
If I have understood your question properly then I think this is the answer.
QTableView *view = new QTableView;
view->setItemDelegateForRow(int row, QAbstractItemDelegate *delegate);

Dynamic search/filter core-list (Polymer 0.5)

I need to implement a filter-type search which hides items in core list if they do not match the search. I created a .hidden class that is applied to an item if an expression returns false:
class = {{ {hidden: !match(model.host, hQuery)} | tokenList }}
The elements are hidden, but the list does not reflow elements unless I click on a visible row. Is there a way to force a reflow using a function call?
After a week of struggling, hiding list items is just not the right way to handle this. Iterate through the original array, push any matching objects to a temporary array, and then replace core-list's .data array with the temporary array: this.$.list_id.data = tmpArray. Performance is good for lists up to 10K records.
This is what I'm doing in my code, and it works:
<div style="{{hide_part1}}">
...content to show/hide...
</div>
....
Switching it based on route change(flatron-director):
routeChanged: function(oldValue, newValue) {
if ('some_route_1' == this.route) {
this.hide_part1 = ''
this.hide_part2 = 'display: none;'
} else if ('some_route_2' == this.route) {
this.hide_part1 = 'display: none;'
this.hide_part2 = ''
}
},
Also using core-list's updateSize() and especially scrollToItem(0), i.e. back to top, here and there helps as I also had problems with the 'reflow':
https://stackoverflow.com/questions/29432700/polymer-core-list-is-not-rendering-some-of-the-elements

In WatiN, how to verify a table's column headers and rows?

Consider this HTML table:
<table id="build-table">
<tr>
<th>Build ID</th>
<th>Build Time</th>
</tr>
<tr>
<td>
5.1
</td>
<td>02.06.2011 13:33:03</td>
</tr>
</table>
How would I verify in WatiN that the table has the correct headers (Build ID and Build Time), and the correct content (in this case, one row containing the given hyperlink and date string)?
Sorry, we created a custom TableHandler, using the basic table building blocks: Here is the sample code:
public TableController(Regex tableControlId)
{ InitializeMembers(Find.ById(tableControlId), true); }
private void InitializeMembers(WatiN.Core.Constraints.AttributeConstraint tableControlId, bool hasColumnHeaders)
{
if (tableControlId == null)
{
throw new ArgumentNullException("tableControlId", "'tableControlId' passed in should not be null.");
}
WatiN.Core.Constraints.AttributeConstraint newTableControlId = tableControlId;
Assert.IsTrue(IE.Table(newTableControlId).Exists, "Table with id '" + newTableControlId.ToString() + "' does not exist on this page.");
_controlId = tableControlId;
_hasColumnHeaders = hasColumnHeaders;
_columnHeaders = (hasColumnHeaders) ? GetTableColumnHeaders() : null;
_totalRows = Table.TableRows.Count;
_totalColumns = GetAllColumnDataFromRow((TableRow)Table.TableRows[0], hasColumnHeaders).Count;
}
private StringCollection GetTableColumnHeaders()
{
return GetAllColumnDataFromRow((TableRow)Table.TableRows[0], true);
}
private StringCollection GetAllColumnDataFromRow(TableRow tableRow, bool isTableHeaderRow)
{
StringCollection RowValues = new StringCollection();
if (tableRow == null)
{
for (int colCounter = 0; colCounter < this.TotalColumns; colCounter++) RowValues.Add(String.Empty);
}
if (isTableHeaderRow)
{
foreach (Element e in tableRow.Elements)
{
if (e.TagName == "TH")
{
RowValues.Add(e.Text);
}
}
}
else
{
foreach (TableCell tc in tableRow.TableCells)
{
if (String.IsNullOrEmpty(tc.Text))
{
RowValues.Add(String.Empty);
}
else
{
RowValues.Add(tc.Text);
}
}
}
//fill up for the missing cells, if any, with blanks
int actualCellsInRow = tableRow.TableCells.Count;
int expectedCellsInRow = this.TotalColumns;
for (int colCounter = actualCellsInRow; colCounter < expectedCellsInRow; colCounter++)
{
RowValues.Add(String.Empty);
}
return RowValues;
}
Hope this helps.
There are at least three ways to do this:
I think Watin provides a tablehandler / tablecontroller related methods using which you can retrieve this information. You might want to search on that topic if you want to take this approach.
Using Xpath query (XML). Since you have the id of the table, you can use a XPath query to reach the node where your header is and verify that using a static string "Build ID" in your code. Same with the other pieces of information.
Regex - Using Regular Expressions, you can check if that text exists on the control / page.
If you view the source of your page, you will know the pattern that you should look for on the page. In fact, a simple Assert.AreEqual(true, new Regex("Build ID")Match.Success) should do the trick. However, this is a check that is purely done to see if the text exists on the page. You will not be looking at anything beyond that. Also, if you have multiple occurrences of the text then you should be considering the array of matches you get before you say, "yep, found it".
Note: You may have to checkout the syntax for using a Regex. The above information is just an abstract of what it would look like.
Cheers.

Farsi/Arabic number to be outputted properly

You have a file that outputs as such:
<div id="first">1</div>
2
<div id="third">
<? $i = 3; echo(i) ?>
</div>
Which outputs:
1
2
3
Now if I want to have an output as below:
?
?
?
Well, I was hoping I could output the Arabic/Farsi version of 1,2,3 instead of '?'. How can I use HTML/CSS convert to numbers to Arabic/Farsi?
And why does everything change except numbers when I change my language (Windows XP)?
If you want to number a list, you could use an ol element and change the list-style-type of it like:
ol {
list-style: arabic-indic;
}
Expanding on ShirzITCo and Kirk Woll's answer above -- which saved my but when client decided all the content in a WordPress CMS should use Eastern-Arabic numerals instead of the Western Arabic they started with:
function recursiveReplace(node) {
if (node.nodeType === 3) { // text node
node.nodeValue = node.nodeValue
.replace(/0/g,'۰')
.replace(/1/g,'۱')
.replace(/2/g,'۲')
.replace(/3/g,'۳')
.replace(/4/g,'۴')
.replace(/5/g,'۵')
.replace(/6/g,'۶')
.replace(/7/g,'۷')
.replace(/8/g,'۸')
.replace(/9/g,'۹');
} else if (node.nodeType === 1) { // element
$(node).contents().each(function () {
recursiveReplace(this);
});
}
}
recursiveReplace(document.body);
There is no automated way to change numbers, or even digits. Set up a mapping between then and convert manually.
Numbers are never localized, because unlike natural language words, Arabic numerals are understood across most of the world.
Simply use CSS:
ol {
list-style-type: persian
}
Use the following JavaScript code. This will replace numbers:
function recursiveReplace(node) {
if (node.nodeType == 3) { // text node
node.nodeValue = node.nodeValue.replace("1", "۱");
} else if (node.nodeType == 1) { // element
$(node).contents().each(function () {
recursiveReplace(this);
});
}
}
recursiveReplace(document.body);