问:
Using Angular "track by $ index" with pagination, filtering and sorting not working
I'm having a problem when trying to use the Smart Table with paging, filtering and searching in my table.

I was working with the table when converting a JSON that consumed a request to an object. In this case, I did:

```<code>$scope.estoque = JSON.parse(data.data);
</code>```

The problem came when I needed to include paging, sorting, and searching. Then using the Smart Table, which until then had been serving me in what I needed.

In case, to use the functionality of it, my table array can not be object as it was previously, it needs to be JSON. Which in the case has the format below:

```<code> $scope.estoqueJSON = data.data;

[
  {
    "EstoqueId": 553,
    "DescricaoEstoque": null,
    "NomeMaterial": "Cabo de Fibra Óptica 04FO Multimodo - Indoor / Outdoor - 62,5/125 Furukawa",
    "CodigoMaterial": "100",
    "Ni": "",
    "QtdMaterial": 3.0,
    "QtdMin": 0.0,
    "Unidade": "m",
    "MaterialId": 1
  }
]
</code>```

Following the tutorial in Smart Table documentation, I created the table below:

```<code><table st-table="estoqueStr" st-set-filter="myStrictFilter" class="table table-striped table-responsive">
                <thead style="text-align:center;">
                    <tr>
                        <th st-sort="CodigoMaterial" style="width:20px; font-weight:bold; text-align:center;">Código</th>
                        <th st-sort="Ni" style="width:20px; font-weight:bold; text-align:center;">Ni</th>
                        <th st-sort="NomeMaterial" style="width:20px; font-weight:bold; text-align:center;">Material</th>
                        <th st-sort="Unidade" style="width:20px; font-weight:bold; text-align:center;">UNI.</th>
                        <th st-sort="QtdMaterial" style="width:20px; font-weight:bold; text-align:center;">Qtd</th>
                        <th st-sort="QtdMin" style="width:20px; font-weight:bold; text-align:center;">Qtd Min.</th>
                    </tr>
                    <tr>
                        <th style="width:20px;">
                            <input style="text-align:center;" st-search="CodigoMaterial" placeholder="Código material" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:20px; text-align:center;">
                            <input style="text-align:center;" st-search="Ni" placeholder="Ni" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:auto; text-align:center;">
                            <input style="text-align:center;" st-search="NomeMaterial" placeholder="Nome material" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:10px; text-align:center;">
                            <input style="text-align:center;" st-search="Unidade" placeholder="Unidade" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:10px; text-align:center;">
                            <input style="text-align:center;" st-search="QtdMaterial" placeholder="Qtde atual" class="input-sm form-control" type="search" />
                        </th>
                        <th style="width:10px; text-align:center;">
                            <input style="text-align:center;" st-search="QtdMin" placeholder="Qtde mínima" class="input-sm form-control" type="search" />
                        </th>

                    </tr>
                </thead>
                <tbody id="" class="">
                    <tr ng-repeat="e in estoqueJSON | filter : paginate | orderBy:sortType:sortReverse | filter:searchField track by $index">
                        <td ng-repeat-start="item in e.value"></td>
                        <td style="text-align:center;">{{item.CodigoMaterial}}</td>
                        <td style="text-align:center;">{{item.Ni}}</td>
                        <td>{{item.NomeMaterial}}</td>
                        <td style="text-align:center;">{{item.Unidade}}</td>
                        <td style="text-align:right; color:black;">
                            <span e-form="tableform" editable-number="e.QtdMaterial" onbeforesave="checkQtdEstoque(e, $data)">{{item.QtdMaterial}}</span>
                        </td>
                        <td style="text-align-last:right; color:black;" ng-repeat-end>
                            <span editable-number="e.QtdMin" e-form="tableform" onbeforesave="checkQtdMin(e, $data)">{{item.QtdMin}}</span>
                        </td>

                    </tr>
                </tbody>
            </table>
</code>```

I do not know why it's not showing any bug in the console, and also does not display the JSON data in my table. Can anyone tell me what I'm doing wrong?

AngularJS: 1.3

UPDATE

Ero answer was right, I just need to convert again my array for object, and then use ng-repeat. I'm still with Smart Table erro for filter (what doesn't work for object array), but I think it's plugin error and I will check on the github forum.

答:
Because your ng-repeat is over a single
 you don't need to use ng-repeat-start and ng-repeat-end. The encapsulating
 tag will already repeat the inner HTML of it. Try taking out those tags and only using item to reference your current object. I changed the below HTML for you (it's untested!):

```<code><tbody id="" class="">
    <tr ng-repeat="item in estoqueJSON | filter : paginate | orderBy:sortType:sortReverse | filter:searchField track by $index">
        <td style="text-align:center;">{{item.CodigoMaterial}}</td>
        <td style="text-align:center;">{{item.Ni}}</td>
        <td>{{item.NomeMaterial}}</td>
        <td style="text-align:center;">{{item.Unidade}}</td>
        <td style="text-align:right; color:black;">
            <span e-form="tableform" editable-number="item.QtdMaterial" onbeforesave="checkQtdEstoque(item, $data)">{{item.QtdMaterial}}</span>
        </td>
        <td style="text-align-last:right; color:black;">
            <span editable-number="item.QtdMin" e-form="tableform" onbeforesave="checkQtdMin(item, $data)">{{item.QtdMin}}</span>
        </td>
   </tr>
</tbody>
</code>```

Body:
I'm having a problem when trying to use the Smart Table with paging, filtering and searching in my table.

I was working with the table when converting a JSON that consumed a request to an object. In this case, I did:

$scope.estoque = JSON.parse(data.data);

The problem came when I needed to include paging, sorting, and searching. Then using the Smart Table, which until then had been serving me in what I needed.

In case, to use the functionality of it, my table array can not be object as it was previously, it needs to be JSON. Which in the case has the format below:

 $scope.estoqueJSON = data.data;

[
  {
    "EstoqueId": 553,
    "DescricaoEstoque": null,
    "NomeMaterial": "Cabo de Fibra Óptica 04FO Multimodo - Indoor / Outdoor - 62,5/125 Furukawa",
    "CodigoMaterial": "100",
    "Ni": "",
    "QtdMaterial": 3.0,
    "QtdMin": 0.0,
    "Unidade": "m",
    "MaterialId": 1
  }
]

Following the tutorial in Smart Table documentation, I created the table below:

                        Código
                        Ni
                        Material
                        UNI.
                        Qtd
                        Qtd Min.

                            <input style="text-align:center;" st-search="CodigoMaterial" placeholder="Código material" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="Ni" placeholder="Ni" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="NomeMaterial" placeholder="Nome material" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="Unidade" placeholder="Unidade" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="QtdMaterial" placeholder="Qtde atual" class="input-sm form-control" type="search" />

                            <input style="text-align:center;" st-search="QtdMin" placeholder="Qtde mínima" class="input-sm form-control" type="search" />

                        {{item.CodigoMaterial}}
                        {{item.Ni}}
                        {{item.NomeMaterial}}
                        {{item.Unidade}}

                            {{item.QtdMaterial}}

                            {{item.QtdMin}}

I do not know why it's not showing any bug in the console, and also does not display the JSON data in my table. Can anyone tell me what I'm doing wrong?

AngularJS: 1.3

UPDATE

Ero answer was right, I just need to convert again my array for object, and then use ng-repeat. I'm still with Smart Table erro for filter (what doesn't work for object array), but I think it's plugin error and I will check on the github forum.

Body:
Because your ng-repeat is over a single <tr> you don't need to use ng-repeat-start and ng-repeat-end. The encapsulating <tr> tag will already repeat the inner HTML of it. Try taking out those tags and only using item to reference your current object. I changed the below HTML for you (it's untested!):

<tbody id="" class="">
    <tr ng-repeat="item in estoqueJSON | filter : paginate | orderBy:sortType:sortReverse | filter:searchField track by $index">
        <td style="text-align:center;">{{item.CodigoMaterial}}</td>
        <td style="text-align:center;">{{item.Ni}}</td>
        <td>{{item.NomeMaterial}}</td>
        <td style="text-align:center;">{{item.Unidade}}</td>
        <td style="text-align:right; color:black;">
            <span e-form="tableform" editable-number="item.QtdMaterial" onbeforesave="checkQtdEstoque(item, $data)">{{item.QtdMaterial}}</span>
        </td>
        <td style="text-align-last:right; color:black;">
            <span editable-number="item.QtdMin" e-form="tableform" onbeforesave="checkQtdMin(item, $data)">{{item.QtdMin}}</span>
        </td>
   </tr>
</tbody>


来源: stackexchange

问:
How to make a Single Use JWT
I am currently making a "forgot password" feature for my project. I'm attaching a JWT to the end of the reset password link that expires after 10 minutes. But I also want that link to only be used once (right after they reset their password). At first I figured I would just update the token expiration once they update their password (stupid) but once I did that, I realized that the token wouldn't update their url or the url in their email! So I'm just wondering if anybody knows of a way to create a single use JWT. Hopefully I gave enough information on what I'm looking for. If not, feel free to ask me to expound. Thanks in advance! </p>

答: You could store the date/time of the last time a password change was made by the user in the db with their record. If the last password change time/date is greater than the time in which the token was created return false for the function. Sure you have to add a little logic but it shouldn't be difficult or extensive. There are better ways to do this which involve refresh tokens and so forth but this seems like a simple fix given the problem. </p>

ContentLicense: CC BY-SA 3.0

Title: How to make a Single Use JWT


问:
AvalonDock not Deserializing LayoutRoot orientation correctly
This is frustrating, trying to figure out if this is a bug or I'm an idiot.

Using AvalonDock 3.3.17121.18230

I have a simple layout of Top, Bottom, Left/Center/Right panels. Everything is fine during initial load with the panel properties specified in XAML. After saving the layout using the .Serialize of XmlLayoutSerializer, everything in the text file looks fine. However, when re-loading the layout using Deserialize, the layout loads improperly and places the Top and Bottom panels to the left and right of the center Left/Center/Right panels.

My layout is one LayoutPanel with Orientation="Vertical", then nested inside are 3 LayoutPanels with Orientation="Horizontal". The first horizontal panel is just the TOP, followed by another horizontal panel containing the 3 Left/Center/Right panels, then the final horizontal panel which is the BOTTOM panel.

It appears that regardless of the Rootpanels layout orientation, it always deserializes it as horizontal, even though it explicitly says vertical.

Initial load from XAML properties - all ok

Contents of serialized file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LayoutRoot>
  <RootPanel Orientation="Vertical">
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane DockHeight="100">
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellTop" IsSelected="True" ContentId="ShellTop" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellLeft" IsSelected="True" ContentId="ShellLeft" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellMain" IsSelected="True" ContentId="ShellMain" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellRight" IsSelected="True" ContentId="ShellRight" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellBottom" IsSelected="True" ContentId="ShellBottom" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
  </RootPanel>
  <TopSide />
  <RightSide />
  <LeftSide />
  <BottomSide />
  <FloatingWindows />
  <Hidden />
</LayoutRoot>
</code>```

After serializing, then deserializing - not ok

Contents of serialized file after saving broken layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LayoutRoot>
  <RootPanel Orientation="Horizontal">
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane DockHeight="100">
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellTop" IsSelected="True" ContentId="ShellTop" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellLeft" IsSelected="True" ContentId="ShellLeft" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellMain" IsSelected="True" ContentId="ShellMain" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellRight" IsSelected="True" ContentId="ShellRight" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellBottom" IsSelected="True" ContentId="ShellBottom" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
  </RootPanel>
  <TopSide />
  <RightSide />
  <LeftSide />
  <BottomSide />
  <FloatingWindows />
  <Hidden />
</LayoutRoot>
</code>```

As you can see, it's like the deserialize method doesn't care that RootPanel Orientation="Vertical" and always loads it like it is RootPanel Orientation="Horizontal"

Can someone please try this to sanity check me, or if I'm going about this wrong let me know. I'm just trying to save the state the is loaded from the XAML properties, I'd have to think this is a bug.

Here's the Grid control of my XAML

```<code><Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Button Grid.Row="0" Grid.Column="0" Content="Save Layout" Click="SaveButton_Click"/>
        <Button Grid.Row="0" Grid.Column="1" Content="Restore Layout" Click="RestoreButton_Click"/>
        <Button Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Content="Default Layout" Click="DefaultButton_Click"/>

        <avalonDock:DockingManager AllowMixedOrientation="True" x:Name="DManager" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Loaded="dockManager_Loaded">
            <avalonDock:LayoutRoot>

                <avalonDock:LayoutPanel Orientation="Vertical">

                    <avalonDock:LayoutPanel Orientation="Horizontal">

                        <avalonDock:LayoutAnchorablePane DockHeight="100">
                        <avalonDock:LayoutAnchorable Title="ShellTop" ContentId="ShellTop">
                            <Button Content="TOP"/>
                        </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                    </avalonDock:LayoutPanel>

                    <avalonDock:LayoutPanel Orientation="Horizontal">

                        <avalonDock:LayoutAnchorablePane>
                            <avalonDock:LayoutAnchorable Title="ShellLeft" ContentId="ShellLeft">
                                <Button Content="LEFT"/>
                            </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                    <avalonDock:LayoutAnchorablePane>
                            <avalonDock:LayoutAnchorable Title="ShellMain" ContentId="ShellMain">
                                <Button Content="MIDDLE"/>
                            </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                        <avalonDock:LayoutAnchorablePane>
                            <avalonDock:LayoutAnchorable Title="ShellRight" ContentId="ShellRight">
                                <Button Content="RIGHT"/>
                            </avalonDock:LayoutAnchorable>
                        </avalonDock:LayoutAnchorablePane>

                    </avalonDock:LayoutPanel>

                    <avalonDock:LayoutPanel Orientation="Horizontal">

                            <avalonDock:LayoutAnchorablePane>
                        <avalonDock:LayoutAnchorable Title="ShellBottom" ContentId="ShellBottom">
                            <Button Content="BOTTOM"/>
                        </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                    </avalonDock:LayoutPanel>

                </avalonDock:LayoutPanel>

            </avalonDock:LayoutRoot>
        </avalonDock:DockingManager>
    </Grid>
</code>```

Code-Behind

```<code>private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    XmlLayoutSerializer layoutSerializer = new XmlLayoutSerializer(DManager);
    using (var writer = new StreamWriter("C:/Users/xxx/Desktop/test.txt"))
    {
        layoutSerializer.Serialize(writer);
    }
}

private void RestoreButton_Click(object sender, RoutedEventArgs e)
{
    XmlLayoutSerializer layoutSerializer = new XmlLayoutSerializer(DManager);
    using (var reader = new StreamReader("C:/Users/xxx/Desktop/test.txt"))
    {
        layoutSerializer.Deserialize(reader);
    }
}
</code>```

答:
Toolkit v3.4 already has a fix for a vertical orientation upon deserializing. Toolkit v3.4 is available today, june 5th 2017.
I suggest you try with it.

――――
Get more controls, features, updates and technical support with Xceed Toolkit Plus for WPF

Body:
This is frustrating, trying to figure out if this is a bug or I'm an idiot.

Using AvalonDock 3.3.17121.18230

I have a simple layout of Top, Bottom, Left/Center/Right panels. Everything is fine during initial load with the panel properties specified in XAML. After saving the layout using the .Serialize of XmlLayoutSerializer, everything in the text file looks fine. However, when re-loading the layout using Deserialize, the layout loads improperly and places the Top and Bottom panels to the left and right of the center Left/Center/Right panels.

My layout is one LayoutPanel with Orientation="Vertical", then nested inside are 3 LayoutPanels with Orientation="Horizontal". The first horizontal panel is just the TOP, followed by another horizontal panel containing the 3 Left/Center/Right panels, then the final horizontal panel which is the BOTTOM panel.

It appears that regardless of the Rootpanels layout orientation, it always deserializes it as horizontal, even though it explicitly says vertical.

Initial load from XAML properties - all ok

Contents of serialized file:

<?xml version="1.0" encoding="utf-8"?>
<LayoutRoot>
  <RootPanel Orientation="Vertical">
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane DockHeight="100">
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellTop" IsSelected="True" ContentId="ShellTop" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellLeft" IsSelected="True" ContentId="ShellLeft" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellMain" IsSelected="True" ContentId="ShellMain" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellRight" IsSelected="True" ContentId="ShellRight" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellBottom" IsSelected="True" ContentId="ShellBottom" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
  </RootPanel>
  <TopSide />
  <RightSide />
  <LeftSide />
  <BottomSide />
  <FloatingWindows />
  <Hidden />
</LayoutRoot>

After serializing, then deserializing - not ok

Contents of serialized file after saving broken layout:

<?xml version="1.0" encoding="utf-8"?>
<LayoutRoot>
  <RootPanel Orientation="Horizontal">
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane DockHeight="100">
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellTop" IsSelected="True" ContentId="ShellTop" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellLeft" IsSelected="True" ContentId="ShellLeft" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellMain" IsSelected="True" ContentId="ShellMain" CanClose="False" />
      </LayoutAnchorablePane>
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellRight" IsSelected="True" ContentId="ShellRight" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
    <LayoutPanel Orientation="Horizontal">
      <LayoutAnchorablePane>
        <LayoutAnchorable AutoHideMinWidth="100" AutoHideMinHeight="100" Title="ShellBottom" IsSelected="True" ContentId="ShellBottom" CanClose="False" />
      </LayoutAnchorablePane>
    </LayoutPanel>
  </RootPanel>
  <TopSide />
  <RightSide />
  <LeftSide />
  <BottomSide />
  <FloatingWindows />
  <Hidden />
</LayoutRoot>

As you can see, it's like the deserialize method doesn't care that RootPanel Orientation="Vertical" and always loads it like it is RootPanel Orientation="Horizontal"

Can someone please try this to sanity check me, or if I'm going about this wrong let me know. I'm just trying to save the state the is loaded from the XAML properties, I'd have to think this is a bug.

Here's the Grid control of my XAML

<Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Button Grid.Row="0" Grid.Column="0" Content="Save Layout" Click="SaveButton_Click"/>
        <Button Grid.Row="0" Grid.Column="1" Content="Restore Layout" Click="RestoreButton_Click"/>
        <Button Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Content="Default Layout" Click="DefaultButton_Click"/>

        <avalonDock:DockingManager AllowMixedOrientation="True" x:Name="DManager" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Loaded="dockManager_Loaded">
            <avalonDock:LayoutRoot>

                <avalonDock:LayoutPanel Orientation="Vertical">

                    <avalonDock:LayoutPanel Orientation="Horizontal">

                        <avalonDock:LayoutAnchorablePane DockHeight="100">
                        <avalonDock:LayoutAnchorable Title="ShellTop" ContentId="ShellTop">
                            <Button Content="TOP"/>
                        </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                    </avalonDock:LayoutPanel>

                    <avalonDock:LayoutPanel Orientation="Horizontal">

                        <avalonDock:LayoutAnchorablePane>
                            <avalonDock:LayoutAnchorable Title="ShellLeft" ContentId="ShellLeft">
                                <Button Content="LEFT"/>
                            </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                    <avalonDock:LayoutAnchorablePane>
                            <avalonDock:LayoutAnchorable Title="ShellMain" ContentId="ShellMain">
                                <Button Content="MIDDLE"/>
                            </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                        <avalonDock:LayoutAnchorablePane>
                            <avalonDock:LayoutAnchorable Title="ShellRight" ContentId="ShellRight">
                                <Button Content="RIGHT"/>
                            </avalonDock:LayoutAnchorable>
                        </avalonDock:LayoutAnchorablePane>

                    </avalonDock:LayoutPanel>

                    <avalonDock:LayoutPanel Orientation="Horizontal">

                            <avalonDock:LayoutAnchorablePane>
                        <avalonDock:LayoutAnchorable Title="ShellBottom" ContentId="ShellBottom">
                            <Button Content="BOTTOM"/>
                        </avalonDock:LayoutAnchorable>
                    </avalonDock:LayoutAnchorablePane>

                    </avalonDock:LayoutPanel>

                </avalonDock:LayoutPanel>

            </avalonDock:LayoutRoot>
        </avalonDock:DockingManager>
    </Grid>

Code-Behind

private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    XmlLayoutSerializer layoutSerializer = new XmlLayoutSerializer(DManager);
    using (var writer = new StreamWriter("C:/Users/xxx/Desktop/test.txt"))
    {
        layoutSerializer.Serialize(writer);
    }
}

private void RestoreButton_Click(object sender, RoutedEventArgs e)
{
    XmlLayoutSerializer layoutSerializer = new XmlLayoutSerializer(DManager);
    using (var reader = new StreamReader("C:/Users/xxx/Desktop/test.txt"))
    {
        layoutSerializer.Deserialize(reader);
    }
}


问:
Google App Maker Query Builder
Created a simple app to keep track of the company fax numbers. In my header I have a search box where I want user's to search either by First Name, Last Name or both First and Last Name. I added the below to Query Builder

firstName contains? :SearchText or
lastName contains? :SearchText

Searching by first name or last name works just fine. How can I search by both first and last name? Right now when I search by both I get no results. Thanks.

答:
"User Picker" widget should be a good fit for your case.

If you want to keep custom employees model please consider the following options:

Add Name field ("FirstName LastName") so contains operator would give expected result

Switch datasource to Query Script and process search query
(https://developers.google.com/appmaker/models/datasources#query_script)

Title: Google App Maker Query Builder


问:
Double for loop in R creating a matrix
I would like to create a 5x5 matrix in R using two for loops.
I have 5 numbers p_j and q_i with i and j in {1,2,3,4,5}.
I would like to create a matrix with where the element in (j,i) is given by p_j * q_j. j-th row and i-th column.
So, first of all I would like to create an empty matrix m and then filling the matrix using the for loops.

for (i in 1:5){   for (j in 1:5){
         } }

答:
Assuming you have variables named "p_1", "p_2" in the working environment:</p>

```<code>mymatrix <- matrix(nrow = 5, ncol = 5)
for (i in 1:5) {
  for (j in 1:5) {
    mymatrix[i, j] <- get(paste("p_", j, sep="")) *
                      get(paste("q_", i, sep=""))
  }
}
</code>```

Title: Double for loop in R creating a matrix

Body:
Assuming you have variables named "p_1", "p_2" in the working environment:

mymatrix <- matrix(nrow = 5, ncol = 5)
for (i in 1:5) {
  for (j in 1:5) {
    mymatrix[i, j] <- get(paste("p_", j, sep="")) *
                      get(paste("q_", i, sep=""))
  }
}


问:
Oracle Query to select only the text between two '-' characters
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

```<code>Description
------------------------------------------
Case 1 - Deleted - The case is closed
</code>```

What I want to have:

```<code>Description
------------------------------------------
Deleted
</code>```

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

```<code>select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );
</code>```

答:
One possible way:</p>

```<code>with t(col) as(
select 'Case # - Reason - Bla Bla' from dual union all
select 'Case # - Reason2 - Bla Bla' from dual
)

select
substr(
    col,
    INSTR (col , '-' , 1, 1)+1,
    INSTR (col , '-' , 1, 2) - INSTR (col , '-' , 1, 1) - 1
)
from t
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

Description
------------------------------------------
Case 1 - Deleted - The case is closed

What I want to have:

Description
------------------------------------------
Deleted

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );

Body:
One possible way:

with t(col) as(
select 'Case # - Reason - Bla Bla' from dual union all
select 'Case # - Reason2 - Bla Bla' from dual
)

select
substr(
    col,
    INSTR (col , '-' , 1, 1)+1,
    INSTR (col , '-' , 1, 2) - INSTR (col , '-' , 1, 1) - 1
)
from t


问:
Spring auto-add 'X-Total-Count' header
I'm using 'admin-on-rest' UI for my Web-application and it has next restriction:

Note: The jsonServer REST client expects the API to include a
  X-Total-Count header in the response to GET_LIST calls. The value must
  be the total number of resources in the collection. This allows
  admin-on-rest to know how many pages of resources there are in total,
  and build the pagination controls.

I solved the problem by adding X-Total-Count header to my list-returning REST-endpoints manually like this:
response.addHeader("X-Total-Count", String.valueOf(outputList.size()));

But I'm wondering: if there's some elegant way to do it automatically in Spring? I mean auto-add this header with proper value when some endpoint returns JSON-list?

答:
Yes, there is! (If you are using spring 4.1 or above).

It's called ResponseBodyAdvice and it enables you to intercept calls (just before response is written and gives access to raw http response).

Basically what you need is to implement controller advice like this:

```<code>@ControllerAdvice
public class ResourceSizeAdvice implements ResponseBodyAdvice<Collection<?>> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //Checks if this advice is applicable.
        //In this case it applies to any endpoint which returns a collection.
        return Collection.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Collection<?> beforeBodyWrite(Collection<?> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        response.getHeaders().add("X-Total-Count", String.valueOf(body.size()));
        return body;
    }
}
</code>```

Title: Spring auto-add 'X-Total-Count' header

Body:
Yes, there is! (If you are using spring 4.1 or above).

It's called ResponseBodyAdvice and it enables you to intercept calls (just before response is written and gives access to raw http response).

Basically what you need is to implement controller advice like this:

@ControllerAdvice
public class ResourceSizeAdvice implements ResponseBodyAdvice<Collection<?>> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //Checks if this advice is applicable.
        //In this case it applies to any endpoint which returns a collection.
        return Collection.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Collection<?> beforeBodyWrite(Collection<?> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        response.getHeaders().add("X-Total-Count", String.valueOf(body.size()));
        return body;
    }
}


问:
How do I fix "remote: fatal error in commit_refs" errors trying to push with Git?
When I try to push to master branch that is hosted on https://github.com I get:

remote: fatal error in commit_refs

How can I solve this?

答:
In my case, GitHub was down by the time I was trying to push.

Just check https://www.githubstatus.com to know about GitHub site status.

When it's up you'll be able to push.


问:
ng-filter with ng-repeat for objects (k, v)
I am using inbuilt Angular 1 filters and trying to filter out a property of an object. I am aware that Angular Filters do not accept an Object rather an Array, however, the way the webapp is designed I cannot refactor so I can pass an array instead of an object. The reason has to do with tracking each object by its value which is quite efficient. The caveat though with the data set is that it is huge. One table can contain up to 1000 rows. To give you a better understanding, my object looks like this:

```<code>{"UNIQUE-KEY-XYZ-123" : {"name" : "XYZ", "type" : "investment", "book", "ABC"}, "UNIQUE-KEY-LMN-321" : {"name" : "LMN", "type" : "investment", "book", "STU"}, ...}
</code>```

```<code><tr><td><input ng-model="foo.book"></td></tr>
<tr ng-repeat="(key, row) in blotter.rows track by key | filter:foo" ng-class="{flash: blotter.flashList[key]['all']}">
</code>```

Filtering works fine if I pass an array rather than the object but help me figure out a way so it works with object too. Some people suggested using this external module but I believe the way it is implemented is very inefficient.

答:
Consider using the ng-change directive to create the filtered object:

```<code><tr>
  <td><input ng-model="foo.book"
             ng-change="filteredRows=myFilter(blotter.rows, foo.book) />
  </td>
</tr>
<tr ng-repeat="(key, row) in filteredRows track by key"
    ng-class="{flash: blotter.flashList[key]['all']}">
</tr>
</code>```

JS

```<code>$scope.myFilter = function(data, selector) {
    var filteredRows = {};
    //Code here
    return filteredRows;
};
</code>```

Using the ng-change directive is more efficient than using the watcher in the ng-repeat and the dirty checking mechanism of the digest cycle.

Body:
I am using inbuilt Angular 1 filters and trying to filter out a property of an object. I am aware that Angular Filters do not accept an Object rather an Array, however, the way the webapp is designed I cannot refactor so I can pass an array instead of an object. The reason has to do with tracking each object by its value which is quite efficient. The caveat though with the data set is that it is huge. One table can contain up to 1000 rows. To give you a better understanding, my object looks like this:

{"UNIQUE-KEY-XYZ-123" : {"name" : "XYZ", "type" : "investment", "book", "ABC"}, "UNIQUE-KEY-LMN-321" : {"name" : "LMN", "type" : "investment", "book", "STU"}, ...}

<input ng-model="foo.book">

Filtering works fine if I pass an array rather than the object but help me figure out a way so it works with object too. Some people suggested using this external module but I believe the way it is implemented is very inefficient.

Body:
Consider using the ng-change directive to create the filtered object:

<tr>
  <td><input ng-model="foo.book"
             ng-change="filteredRows=myFilter(blotter.rows, foo.book) />
  </td>
</tr>
<tr ng-repeat="(key, row) in filteredRows track by key"
    ng-class="{flash: blotter.flashList[key]['all']}">
</tr>

JS

$scope.myFilter = function(data, selector) {
    var filteredRows = {};
    //Code here
    return filteredRows;
};

Using the ng-change directive is more efficient than using the watcher in the ng-repeat and the dirty checking mechanism of the digest cycle.


问:
Decoding multiple encoded string
How do I decode this to get the result below?

```<code>/browse_ajax?action_continuation=1\u0026amp;continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA%253D%253D

/browse_ajax?action_continuation=1&continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA%253D%253D
</code>```

I've tried these, also using them multiple times as I did read strings may be encoded multiple times.

```<code>System.Text.RegularExpressions.Regex.Unescape(string)
System.Uri.UnescapeDataString(string)
System.Net.WebUtility.UrlDecode(string)
</code>```

Which is the right function here or rather in what order do I need to call them to get that result. As the strings vary there may be other special characters in the set so doing a workaround, editing it myself, is somewhat too risky.

The string has to be decoded to work with new System.Net.WebClient().DownloadString(string).

EDIT: So I found out the above statement is wrong, I do not have to decode this to use WebClient.DownloadString(string). However the downloaded string suffers similar encoding too. Setting the WebClient's Encoding property to UTF8 inbefore downloading does most of the job, however some characters still seem corrupted, for example: Double quotes and ampersand stay \u0026quot; and \u0026amp;.

I don't know how to make \u0026 to &, so I can change & amp; to &.

答:
That these strings are double (actually triple) encoded in this way is a sign that the string is not being encoded correctly. If you own the code that encodes these strings, consider solving this problem there, which is the root of the issue.

That said, here are the decoding calls you need to make to decode this. I do not recommend this solution, as it is definitely a workaround. Again, the problematic behavior is in the code doing the encoding.

```<code>string val = "/browse_ajax?action_continuation=1\u0026amp;continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA%253D%253D";
val = System.Uri.UnescapeDataString(val);
val = System.Uri.UnescapeDataString(val);
val = System.Web.HttpUtility.HtmlDecode(val);
</code>```

This will give you:

```<code>/browse_ajax?action_continuation=1&continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA==
</code>```

If you really want to keep the %253D encoding of the equal signs, just call Uri.UnescapeData(string) once. This will leave the equal signs encoded, except as %3D, which is their proper encoded value.

Title: Decoding multiple encoded string

Body:
How do I decode this to get the result below?

/browse_ajax?action_continuation=1\u0026amp;continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA%253D%253D

/browse_ajax?action_continuation=1&continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA%253D%253D

I've tried these, also using them multiple times as I did read strings may be encoded multiple times.

System.Text.RegularExpressions.Regex.Unescape(string)
System.Uri.UnescapeDataString(string)
System.Net.WebUtility.UrlDecode(string)

Which is the right function here or rather in what order do I need to call them to get that result. As the strings vary there may be other special characters in the set so doing a workaround, editing it myself, is somewhat too risky.

The string has to be decoded to work with new System.Net.WebClient().DownloadString(string).

EDIT: So I found out the above statement is wrong, I do not have to decode this to use WebClient.DownloadString(string). However the downloaded string suffers similar encoding too. Setting the WebClient's Encoding property to UTF8 inbefore downloading does most of the job, however some characters still seem corrupted, for example: Double quotes and ampersand stay \u0026quot; and \u0026amp;.

I don't know how to make \u0026 to &, so I can change & amp; to &.

Body:
That these strings are double (actually triple) encoded in this way is a sign that the string is not being encoded correctly. If you own the code that encodes these strings, consider solving this problem there, which is the root of the issue.

That said, here are the decoding calls you need to make to decode this. I do not recommend this solution, as it is definitely a workaround. Again, the problematic behavior is in the code doing the encoding.

string val = "/browse_ajax?action_continuation=1\u0026amp;continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA%253D%253D";
val = System.Uri.UnescapeDataString(val);
val = System.Uri.UnescapeDataString(val);
val = System.Web.HttpUtility.HtmlDecode(val);

This will give you:

/browse_ajax?action_continuation=1&continuation=4qmFsgJAEhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA==

If you really want to keep the %253D encoding of the equal signs, just call Uri.UnescapeData(string) once. This will leave the equal signs encoded, except as %3D, which is their proper encoded value.


问:
Is there a way to substitute a string name for a key “value” in buckets of aggregation results
Here is the aggregation:

```<code> "aggs" : {
 "bucketA" : {
 "terms" : { "field" : "field1" }
 }
</code>```

Here is the results:

```<code> "bucketA": {
 "doc_count_error_upper_bound": 0,
 "sum_other_doc_count": 0,
 "buckets": [
 {
 "key": "value1",
 "doc_count": 667
 },
 {
 "key": "value2",
 "doc_count": 328
 },
 {
 "key": "value3",
 "doc_count": 1
 }
 ]
 }
</code>```

I want to have a file (I imagine store in Elasticsearch somewhere?) that contains the replacement values:

```<code>"value1" : "replacement1"
"value2" : "replacement2"
"value3" : "replacement3"
</code>```

Is there a way to specify this in the "aggregation", or do I have to capture the result and do the substitution subsequently?

答: If you want to apply this substitution only for aggregation, then no, you should do it on the client side. If it's ok to substitute the terms when you index your documents, then you can use synonyms token filter, but it will affect the search results. See details here: https://www.elastic.co/guide/en/elasticsearch/guide/current/using-synonyms.html

Body:
Here is the aggregation:

 "aggs" : {
 "bucketA" : {
 "terms" : { "field" : "field1" }
 }

Here is the results:

 "bucketA": {
 "doc_count_error_upper_bound": 0,
 "sum_other_doc_count": 0,
 "buckets": [
 {
 "key": "value1",
 "doc_count": 667
 },
 {
 "key": "value2",
 "doc_count": 328
 },
 {
 "key": "value3",
 "doc_count": 1
 }
 ]
 }

I want to have a file (I imagine store in Elasticsearch somewhere?) that contains the replacement values:

"value1" : "replacement1"
"value2" : "replacement2"
"value3" : "replacement3"

Is there a way to specify this in the "aggregation", or do I have to capture the result and do the substitution subsequently?


问:
VBScript Replace for character string of unknown length
I am working in Excel to take a faulty URL and replace the incorrect characters.  The characters I want to replace are "%20" BUT there is no way to know how many of those characters will be in the string.  There might be just one "%20" or 5 "%20%20%20%20%20" or any other number of them in between but no matter how many "%20" characters there are I want to replace with only ONE forward slash "/".

I know I can use something like below, but don't want to end up with more than one forward slash if there are more than one "%20"

```<code>Sub fixURL()

Worksheets("Google Feed Original").Activate

 Worksheets("Google Feed Original").Columns("N").Replace _
        What:="%20", replacement:="/", LookAt:=xlPart

End Sub
</code>```

For example the starting URL might look like:

http://domainname.com/products/prodName%20%20%20ProdNumber

and no matter how many "%20" are in the middle, I am trying to get it to format like this instead:

http://domainname.com/products/prodName/ProdNumber

Is there some way I can replace all of them with just one "/" no matter how many "%20" are in the string?

Thanks.

答: You could write a recursive function that will perform the Replace call so long as there are duplicate instances of the / character.  It has been years since I have written VBScript, but I do not remember a function to do that type of replacement built into the language.

Body:
I am working in Excel to take a faulty URL and replace the incorrect characters.  The characters I want to replace are "%20" BUT there is no way to know how many of those characters will be in the string.  There might be just one "%20" or 5 "%20%20%20%20%20" or any other number of them in between but no matter how many "%20" characters there are I want to replace with only ONE forward slash "/".

I know I can use something like below, but don't want to end up with more than one forward slash if there are more than one "%20"

Sub fixURL()

Worksheets("Google Feed Original").Activate

 Worksheets("Google Feed Original").Columns("N").Replace _
        What:="%20", replacement:="/", LookAt:=xlPart

End Sub

For example the starting URL might look like:

http://domainname.com/products/prodName%20%20%20ProdNumber

and no matter how many "%20" are in the middle, I am trying to get it to format like this instead:

http://domainname.com/products/prodName/ProdNumber

Is there some way I can replace all of them with just one "/" no matter how many "%20" are in the string?

Thanks.


问:
How to auto create Sheet Name based in names in column A in Sheet1 in google spreadsheet?
I'm still learning GoogleApp scripting by myself. Can anyone guide me in the right direction how to edit the below script in such a way that instead of naming the new sheet as per the current date, it takes the names from the column A of Sheet1 and then rename it.

Note that i keep on updating column A with new name in new cells down the column off an on.

Thank you for your help in advance!

This is the script I have which works for dates only:

```<code>function onOpen() {
var menu = [{name: "Add", functionName: "newSheet"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet() {
var sheetName = formatDate();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var templateSheet = ss.getActiveSheet();
ss.insertSheet(sheetName, ss.getSheets().length, {template: templateSheet});
}

function formatDate() {
var month, day, d = new Date();
month = ('0'+(d.getUTCMonth()+1)).slice(-2);
day = ('0'+d.getUTCDate()).slice(-2);
return d.getUTCFullYear()+'-'+month+'-'+day;
}
</code>```

答:
The code below gets all the values in col A from A2:A, filters them to ignore blank cells in the data and then checks if the sheets already exist if they already exist nothing happens. If the sheets don't exist it copies the template sheet, renames it and puts it at the end of the sheet tabs.</p>

```<code>function onOpen() {
    var menu = [{
            name : "Add",
            functionName : "newSheet"
        }
    ];
    SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var templateSheet = ss.getActiveSheet();
    var sheet1 = ss.getSheetByName("Sheet1")
        var getNames = sheet1.getRange("A2:A").getValues().filter(String).toString().split(",");

    for (var i = 0; i < getNames.length; i++) {
        var copy = ss.getSheetByName(getNames[i]);
        if (copy) {
            Logger.log("Sheet already exists");
        } else {
            templateSheet.copyTo(ss).setName(getNames[i]);
            ss.setActiveSheet(ss.getSheetByName(getNames[i]));
            ss.moveActiveSheet(ss.getNumSheets());
        }
    }
}
</code>```

Body:
I'm still learning GoogleApp scripting by myself. Can anyone guide me in the right direction how to edit the below script in such a way that instead of naming the new sheet as per the current date, it takes the names from the column A of Sheet1 and then rename it.

Note that i keep on updating column A with new name in new cells down the column off an on.

Thank you for your help in advance!

This is the script I have which works for dates only:

function onOpen() {
var menu = [{name: "Add", functionName: "newSheet"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet() {
var sheetName = formatDate();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var templateSheet = ss.getActiveSheet();
ss.insertSheet(sheetName, ss.getSheets().length, {template: templateSheet});
}

function formatDate() {
var month, day, d = new Date();
month = ('0'+(d.getUTCMonth()+1)).slice(-2);
day = ('0'+d.getUTCDate()).slice(-2);
return d.getUTCFullYear()+'-'+month+'-'+day;
}

Body:
The code below gets all the values in col A from A2:A, filters them to ignore blank cells in the data and then checks if the sheets already exist if they already exist nothing happens. If the sheets don't exist it copies the template sheet, renames it and puts it at the end of the sheet tabs.

function onOpen() {
    var menu = [{
            name : "Add",
            functionName : "newSheet"
        }
    ];
    SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var templateSheet = ss.getActiveSheet();
    var sheet1 = ss.getSheetByName("Sheet1")
        var getNames = sheet1.getRange("A2:A").getValues().filter(String).toString().split(",");

    for (var i = 0; i < getNames.length; i++) {
        var copy = ss.getSheetByName(getNames[i]);
        if (copy) {
            Logger.log("Sheet already exists");
        } else {
            templateSheet.copyTo(ss).setName(getNames[i]);
            ss.setActiveSheet(ss.getSheetByName(getNames[i]));
            ss.moveActiveSheet(ss.getNumSheets());
        }
    }
}


问:
Retrieve Values From List In Entity Framework
There are two different models in my project: Movie and Actor.  Movie has a list of actors and Actor has a list of movies.  What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.

So, to get the information, I use:

```<code>var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);
</code>```

The problem is that while the list ActingCredits is not null, there are no values in it.  Is there something that I am missing to load the values in the list?  ActingCredits is an ICollection<Movie>.

```<code> public class Actor : ModelBase
 {
     public ICollection<Movie> ActingCredits { get; set; }
 }

public class Movie : ModelBase
{
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public Genre Genre { get; set; }
    public int RunTime { get; set; }
    public int Sales { get; set; }
    public ICollection<Actor> Cast { get; set; }
}
</code>```

EDIT: It has come to my attention that this may be wrong and is the cause of the issue.

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
    }
</code>```

答:
The problem was with the database and how I initialized it.

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany(p => p.ActingCredits);
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany(m => m.Cast);

    }
</code>```

Thanks to all who commented. I believe I understand entity framework a whole lot more now.

Body:
There are two different models in my project: Movie and Actor.  Movie has a list of actors and Actor has a list of movies.  What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.

So, to get the information, I use:

var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);

The problem is that while the list ActingCredits is not null, there are no values in it.  Is there something that I am missing to load the values in the list?  ActingCredits is an ICollection<Movie>.

 public class Actor : ModelBase
 {
     public ICollection<Movie> ActingCredits { get; set; }
 }

public class Movie : ModelBase
{
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public Genre Genre { get; set; }
    public int RunTime { get; set; }
    public int Sales { get; set; }
    public ICollection<Actor> Cast { get; set; }
}

EDIT: It has come to my attention that this may be wrong and is the cause of the issue.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
    }

Body:
The problem was with the database and how I initialized it.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany(p => p.ActingCredits);
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany(m => m.Cast);

    }

Thanks to all who commented. I believe I understand entity framework a whole lot more now.


问:
Can't get picture veritcally centered in a div
Yet again, I can't get an image to center inside a specific div. The answers I've come across only center it horizontally, but not vertically

#wrap {
width: auto;
margin: 0 auto;
overflow: hidden;
float: left;
}
/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
width: 50%;
height: 500px;
background: #000;
float: left;
}

#leftBlock img {
display: block;
margin: auto;
transition: transform 4s;
}

#leftBlock img:hover {
transform: scale(1.8);
}

#rightBlock {
width: 50%;
height: 500px;
background: #8ab78f;
float: left;
}

#rightBlock img {
display: block;
margin: auto;
}

/*ignore footer*/
#footerBlock {
height: 200px;
background:  #29342a ;
clear: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
<div id="headerBlock">
    <div class="headerText">blah blah blah so neat</div>
    <div class="headerImg"><img src="/yupyup.jpg" height="70" width="70">
    </div>
</div>

<div id="leftBlock">
    <img src="/leftside.jpg" height="250" width="250">
</div>

<div id="rightBlock"></div>
     <img src="/rightside.jpg" height="250" width="250">
<div id="footerBlock"></div>

</div></code>```

The issue I'm coming across is, it only likes to center it horizontally. The only solution i found was doing the following below, but all that's really doing is moving it all over the screen and me having to pin point where it goes (which should be inside that leftBlock div..) :

```<code>#leftBlock img {
position: absolute;
top: 50%;
margin-top: 305px;
left: 50%;
margin-left: -450px;
transition: transform 4s;
}
</code>```

答:
If I understand the end goal, you want to add position: relative to the parent, remove the margins on the image and use transform: translate(-50%,-50%) combined with top: 50%; left: 50% to center the image relative to the parent.

#wrap {
  width: auto;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
  width: 50%;
  height: 500px;
  background: #000;
  float: left;
}

#leftBlock img {
  display: block;
  margin: auto;
  transition: transform 4s;
}

#leftBlock img:hover {
  transform: translate(-50%,-50%) scale(1.8);
}

#rightBlock {
  width: 50%;
  height: 500px;
  background: #8ab78f;
  float: left;
}

#rightBlock img {
  display: block;
  margin: auto;
}

/*ignore footer*/

#footerBlock {
  height: 200px;
  background: #29342a;
  clear: left;
}

#leftBlock {
  position: relative;
}

#leftBlock img {
  position: absolute;
  top: 50%;
  left: 50%;
  transition: transform 4s;
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
<div id="headerBlock">
    <div class="headerText">blah blah blah so neat</div>
    <div class="headerImg"><img src="/yupyup.jpg" height="70" width="70">
    </div>
</div>

<div id="leftBlock">
    <img src="/leftside.jpg" height="250" width="250">
</div>

<div id="rightBlock"></div>
     <img src="/rightside.jpg" height="250" width="250">
<div id="footerBlock"></div>

</div></code>```

Body:
Yet again, I can't get an image to center inside a specific div. The answers I've come across only center it horizontally, but not vertically

#wrap {
width: auto;
margin: 0 auto;
overflow: hidden;
float: left;
}
/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
width: 50%;
height: 500px;
background: #000;
float: left;
}

#leftBlock img {
display: block;
margin: auto;
transition: transform 4s;
}

#leftBlock img:hover {
transform: scale(1.8);
}

#rightBlock {
width: 50%;
height: 500px;
background: #8ab78f;
float: left;
}

#rightBlock img {
display: block;
margin: auto;
}

/*ignore footer*/
#footerBlock {
height: 200px;
background:  #29342a ;
clear: left;
}

blah blah blah so neat

The issue I'm coming across is, it only likes to center it horizontally. The only solution i found was doing the following below, but all that's really doing is moving it all over the screen and me having to pin point where it goes (which should be inside that leftBlock div..) :

#leftBlock img {
position: absolute;
top: 50%;
margin-top: 305px;
left: 50%;
margin-left: -450px;
transition: transform 4s;
}

Body:
If I understand the end goal, you want to add position: relative to the parent, remove the margins on the image and use transform: translate(-50%,-50%) combined with top: 50%; left: 50% to center the image relative to the parent.

#wrap {
  width: auto;
  margin: 0 auto;
  overflow: hidden;
  float: left;
}

/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
  width: 50%;
  height: 500px;
  background: #000;
  float: left;
}

#leftBlock img {
  display: block;
  margin: auto;
  transition: transform 4s;
}

#leftBlock img:hover {
  transform: translate(-50%,-50%) scale(1.8);
}

#rightBlock {
  width: 50%;
  height: 500px;
  background: #8ab78f;
  float: left;
}

#rightBlock img {
  display: block;
  margin: auto;
}

/*ignore footer*/

#footerBlock {
  height: 200px;
  background: #29342a;
  clear: left;
}

#leftBlock {
  position: relative;
}

#leftBlock img {
  position: absolute;
  top: 50%;
  left: 50%;
  transition: transform 4s;
  transform: translate(-50%, -50%);
}

<div id="wrap">
<div id="headerBlock">
    <div class="headerText">blah blah blah so neat</div>
    <div class="headerImg"><img src="/yupyup.jpg" height="70" width="70">
    </div>
</div>

<div id="leftBlock">
    <img src="/leftside.jpg" height="250" width="250">
</div>

<div id="rightBlock"></div>
     <img src="/rightside.jpg" height="250" width="250">
<div id="footerBlock"></div>

</div>


问:
Swift 3 UITableView not updating after deleting from Firebase
I'm trying to delete items from a Firebase database when user swipes to delete on the UITableView.

I'm also using the nifty showActivityIndicator and hideActivityIndicator functions from https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift in order to easily show and hide the activity indicator.

I can see both the database record as well as the JPG file properly deleted from Firebase when the following code is run.

But the problem is that the activity indicator never disappears from the screen, and the UITableView does not refresh.

In fact, the

```<code>print("Stopping activity indicator")
</code>```

and

```<code>print("Reloading table view")
</code>```

do not even run.

What am I doing wrong?

```<code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let alert = UIAlertController(title: "Delete Task", message: "Do you want to delete this task?", preferredStyle: .alert)
            let confirmAction = UIAlertAction(title:"OK", style: .default) { action in
                // Show activity indicator
                ViewControllerUtils().showActivityIndicator(uiView: self.view)

                // Retrieve Firebase reference to delete
                let repairItem = self.repairItems[indexPath.row]
                let storage = Storage.storage()
                let storageRef = storage.reference()
                let imageRef = storageRef.child(repairItem.imageRef)

                // Delete the item from Firebase
                repairItem.ref?.removeValue(completionBlock: {(error, ref) in
                    if let error = error {
                        print("Problem deleting item")
                    } else {
                        print("Item deleted successfully")
                    }
                })

                // Delete the photo
                imageRef.delete { error in
                    if let error = error {
                        print("Problem deleting photo")
                    } else {
                        print("Photo deleted successfully")
                    }
                }

                print("Stopping activity indicator")
                // Stop the activity indicator
                ViewControllerUtils().hideActivityIndicator(uiView: self.view)

                print("Reloading table view")
                // Reloading table view
                self.tableView.reloadData()
            }

            let cancelAction = UIAlertAction(title: "Cancel", style: .default)

            alert.addAction(confirmAction)
            alert.addAction(cancelAction)

            present(alert, animated: true, completion: nil)
        }
    }
</code>```

答:
When it comes to keeping a tableView and Firebase synchronized, there are two main options:

1) When removing a node from Firebase, manually remove it from the
  tableView datasource when removing it from Firebase. No observer needed.

2) Attach a remove event observer to Firebase so when a node is removed,
  your App will receive an event of which node it was, and remove it.

Here's an example; I am leaving the tableView code out for the sake of brevity.

Suppose we have a tableView that displays users. The tableView has a dataSource of usersArray which contain UserClass objects.

Given a Firebase structure

```<code>users
  user_0
    name: "Frank"
  user_2
    name: "Bill"
  user_3
    name: "Hugh"
</code>```

We add three observers to the users node, childAdded, childChanged, childRemoved

```<code>class UserClass {
    var key = ""
}

var usersArray = [UserClass]()

let usersRef = self.ref.child("users")

usersRef.observe(.childAdded, with: { snapshot in
    let user = UserClass()
    user.key = snapshot.key
    self.usersArray.append(user)
    self.tableView.reloadData()
})

usersRef.observe(.childChanged, with: { snapshot in
    if let index = self.usersArray.index(where: {$0.key == snapshot.key}) {
        //update it in the array via the index
        self.tableView.reloadData()
    } else {
        //item not found
    }
})

usersRef.observe(.childRemoved, with: { snapshot in
    if let index = self.usersArray.index(where: {$0.key == snapshot.key}) {
        self.usersArray.remove(at: index) //remove it from the array via the index
        self.tableView.reloadUI()
    } else {
        item not found
    }
})
</code>```

If a user is added, the .childAdded observer receives the new user so it can be appended to the array.

If a user is changed, the .childChanged observer receives the changed user. Grab the key, which would typically be the uid, locate it in the array and update the properties.

If a user is removed, the .childRemoved observer receives the removed user. Grab the key, locate it in the array and remove it.

In each case, reload the tableView after the change to the dataSource.

Body:
I'm trying to delete items from a Firebase database when user swipes to delete on the UITableView.

I'm also using the nifty showActivityIndicator and hideActivityIndicator functions from https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift in order to easily show and hide the activity indicator.

I can see both the database record as well as the JPG file properly deleted from Firebase when the following code is run.

But the problem is that the activity indicator never disappears from the screen, and the UITableView does not refresh.

In fact, the

print("Stopping activity indicator")

and

print("Reloading table view")

do not even run.

What am I doing wrong?

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let alert = UIAlertController(title: "Delete Task", message: "Do you want to delete this task?", preferredStyle: .alert)
            let confirmAction = UIAlertAction(title:"OK", style: .default) { action in
                // Show activity indicator
                ViewControllerUtils().showActivityIndicator(uiView: self.view)

                // Retrieve Firebase reference to delete
                let repairItem = self.repairItems[indexPath.row]
                let storage = Storage.storage()
                let storageRef = storage.reference()
                let imageRef = storageRef.child(repairItem.imageRef)

                // Delete the item from Firebase
                repairItem.ref?.removeValue(completionBlock: {(error, ref) in
                    if let error = error {
                        print("Problem deleting item")
                    } else {
                        print("Item deleted successfully")
                    }
                })

                // Delete the photo
                imageRef.delete { error in
                    if let error = error {
                        print("Problem deleting photo")
                    } else {
                        print("Photo deleted successfully")
                    }
                }

                print("Stopping activity indicator")
                // Stop the activity indicator
                ViewControllerUtils().hideActivityIndicator(uiView: self.view)

                print("Reloading table view")
                // Reloading table view
                self.tableView.reloadData()
            }

            let cancelAction = UIAlertAction(title: "Cancel", style: .default)

            alert.addAction(confirmAction)
            alert.addAction(cancelAction)

            present(alert, animated: true, completion: nil)
        }
    }

Body:
When it comes to keeping a tableView and Firebase synchronized, there are two main options:

1) When removing a node from Firebase, manually remove it from the
  tableView datasource when removing it from Firebase. No observer needed.

2) Attach a remove event observer to Firebase so when a node is removed,
  your App will receive an event of which node it was, and remove it.

Here's an example; I am leaving the tableView code out for the sake of brevity.

Suppose we have a tableView that displays users. The tableView has a dataSource of usersArray which contain UserClass objects.

Given a Firebase structure

users
  user_0
    name: "Frank"
  user_2
    name: "Bill"
  user_3
    name: "Hugh"

We add three observers to the users node, childAdded, childChanged, childRemoved

class UserClass {
    var key = ""
}

var usersArray = [UserClass]()

let usersRef = self.ref.child("users")

usersRef.observe(.childAdded, with: { snapshot in
    let user = UserClass()
    user.key = snapshot.key
    self.usersArray.append(user)
    self.tableView.reloadData()
})

usersRef.observe(.childChanged, with: { snapshot in
    if let index = self.usersArray.index(where: {$0.key == snapshot.key}) {
        //update it in the array via the index
        self.tableView.reloadData()
    } else {
        //item not found
    }
})

usersRef.observe(.childRemoved, with: { snapshot in
    if let index = self.usersArray.index(where: {$0.key == snapshot.key}) {
        self.usersArray.remove(at: index) //remove it from the array via the index
        self.tableView.reloadUI()
    } else {
        item not found
    }
})

If a user is added, the .childAdded observer receives the new user so it can be appended to the array.

If a user is changed, the .childChanged observer receives the changed user. Grab the key, which would typically be the uid, locate it in the array and update the properties.

If a user is removed, the .childRemoved observer receives the removed user. Grab the key, locate it in the array and remove it.

In each case, reload the tableView after the change to the dataSource.


问:
Finding the median of an array of floating point numbers
I've looked through all the examples in here already of this and nothing quite answers my question. I'm very new to Groovy.

I want to create something like a list or an array of floating point numbers, prices such as 239.99.

I then want to pass that array or list to a method that will determine the median price in that array or list of numbers. The total size will vary.

Is there any quick and easy code to do this? How do I add each number to the array or list and must I use doubles?

Any help is appreciated, this one has me stuck and frustrated.

Thanks!

答:
The following function determines the median for non-empty lists.

```<code>def median(data) {
    def copy = data.toSorted()
    def middle = data.size().intdiv(2)

    // you can omit the return in groovy for the last statement
    data.size() % 2 ? copy[middle] : (copy[middle - 1] + copy[middle]) / 2
}
</code>```

It works with all types that support addition and division.

For example:

```<code>assert median([1, 7, 4, 3]) == 3.5
assert median([1, 7, 4]) == 4
assert median([1, 7]) == 4
assert median([1]) == 1
assert median([1.7, 3.4, 10.9, 4.2]) == 3.8
</code>```

In terms of what you can do with lists check the Lists overview and then the List API.

Body:
The following function determines the median for non-empty lists.

def median(data) {
    def copy = data.toSorted()
    def middle = data.size().intdiv(2)

    // you can omit the return in groovy for the last statement
    data.size() % 2 ? copy[middle] : (copy[middle - 1] + copy[middle]) / 2
}

It works with all types that support addition and division.

For example:

assert median([1, 7, 4, 3]) == 3.5
assert median([1, 7, 4]) == 4
assert median([1, 7]) == 4
assert median([1]) == 1
assert median([1.7, 3.4, 10.9, 4.2]) == 3.8

In terms of what you can do with lists check the Lists overview and then the List API.


问:
Why am I getting an UnboundLocalError in the except clause of my Python script?
I have the following part of code from a Python script.

```<code>status = 'success'
try:
 sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
  #traceback.print_exc()
  error_message = e
#  print str(e)
  status = 'fail'
print ("{},{},{},{}".format(hivedb,table,status,error_message))
sys.exit(1)
</code>```

Here in this part of code, if there is an exception then I am setting error_message.

If there is no error, then I get UnboundLocalError: local variable 'e' referenced before assignment.

What I want is if there is no error, I want the error_message set to No error.

How can I achieve that?

答:
You need to define error_message before the try/catch block as you have already for status:

```<code>status = 'success'
error_message = 'No error'
try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    error_message = e
    status = 'fail'
</code>```

Body:
I have the following part of code from a Python script.

status = 'success'
try:
 sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
  #traceback.print_exc()
  error_message = e
#  print str(e)
  status = 'fail'
print ("{},{},{},{}".format(hivedb,table,status,error_message))
sys.exit(1)

Here in this part of code, if there is an exception then I am setting error_message.

If there is no error, then I get UnboundLocalError: local variable 'e' referenced before assignment.

What I want is if there is no error, I want the error_message set to No error.

How can I achieve that?

Body:
You need to define error_message before the try/catch block as you have already for status:

status = 'success'
error_message = 'No error'
try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    error_message = e
    status = 'fail'


问:
Visual Studio 2017 - Git failed with a fatal error
I am using Visual Studio 2017 Community Edition (CE), and I have signed into my Microsoft account and I am connected to VSTS. I can see all my projects and repositories, but when I attempt to pull/fetch/push any changes I get the following error:

```<code>Error encountered while pushing to the remote repository: Git failed with a fatal error.
PushCommand.ExecutePushCommand
</code>```

And accordingly for the fetch and pull commands too.

I installed Git for Windows on the Visual Studio 2017 installer and not only is it failing to work with VSTS, I am unable to work with any of my GitHub repositories too. Has anyone else noticed this? It's happened on two of my machines so far.

Visual Studio 2015 Enterprise Edition (EE) and CE work completely fine for me.

It seems that this issue has gotten far more recognition that I thought it would which leads me to believe that this is an issue with how Visual Studio is dealing with Git. I have also noticed that every time I update Visual Studio, this problem pops back up, and I have to go through the steps in some of the answers below to get Git working again. I'm not sure why this is happening, and I also don't know if Microsoft are planning to resolving this issue.

答: I had the same issue. Restarting Visual studio worked for me... You may try it before reinstalling stuff.

Body:
I am using Visual Studio 2017 Community Edition (CE), and I have signed into my Microsoft account and I am connected to VSTS. I can see all my projects and repositories, but when I attempt to pull/fetch/push any changes I get the following error:

Error encountered while pushing to the remote repository: Git failed with a fatal error.
PushCommand.ExecutePushCommand

And accordingly for the fetch and pull commands too.

I installed Git for Windows on the Visual Studio 2017 installer and not only is it failing to work with VSTS, I am unable to work with any of my GitHub repositories too. Has anyone else noticed this? It's happened on two of my machines so far.

Visual Studio 2015 Enterprise Edition (EE) and CE work completely fine for me.

It seems that this issue has gotten far more recognition that I thought it would which leads me to believe that this is an issue with how Visual Studio is dealing with Git. I have also noticed that every time I update Visual Studio, this problem pops back up, and I have to go through the steps in some of the answers below to get Git working again. I'm not sure why this is happening, and I also don't know if Microsoft are planning to resolving this issue.


问:
Rename property of an object inside array
This is my input JSON

```<code>{
"uuid":123,
"description": [
    {
        "car_name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}
</code>```

Expected output:

```<code>{
"uuid":123,
"description": [
    {
        "name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}
</code>```

Rule : .description[]|={name:.car_name,saleDate}

I am able to achieve the desired result with this rule. However, is there a way I can rename the 'car_name' property to 'name' and also not mention all the other properties ( in this case, 'saleDate') in the rule. I might end up having 50+ properties inside the object and I do not want to mention all of them in the rule.

There can be more than one object in the array.

答:
Does this do what you want?

```<code> jq '.description[]
     |= . +
       if has("car_name") then {"name":.car_name}
       else null end
     | del(.description[].car_name)'
</code>```

The if-then block adds the object {name:.car_name} to any object in the description array that has a key with the name "car_name" and adds nothing (null) to any object in the array that does not have a key with that name.

The del function deletes key-value pairs at the path expression .description[].car_name

Body:
This is my input JSON

{
"uuid":123,
"description": [
    {
        "car_name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Expected output:

{
"uuid":123,
"description": [
    {
        "name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Rule : .description[]|={name:.car_name,saleDate}

I am able to achieve the desired result with this rule. However, is there a way I can rename the 'car_name' property to 'name' and also not mention all the other properties ( in this case, 'saleDate') in the rule. I might end up having 50+ properties inside the object and I do not want to mention all of them in the rule.

There can be more than one object in the array.

Body:
Does this do what you want?

 jq '.description[]
     |= . +
       if has("car_name") then {"name":.car_name}
       else null end
     | del(.description[].car_name)'

The if-then block adds the object {name:.car_name} to any object in the description array that has a key with the name "car_name" and adds nothing (null) to any object in the array that does not have a key with that name.

The del function deletes key-value pairs at the path expression .description[].car_name


问:
How to change the Angular Material 2 CSS imports order?
On an Angular 2 app, built with Angular CLI, I've set up the Angular 2 Material components following the official installation guide.

Angular 2 Material is placing its main CSS styles in the page  always below my custom CSS styles. Which creates implications on my side if I need to override them.

How can I force Angular 2 Material to place its core CSS styles above the styles which I defined inside my Angular CLI main (entry) CSS file?

答:
I think the issue you are having is due to having some references to your css files in the index.html and having others in the angular-cli.json file.

Below is an example of my angular.cli json file and index.html

Whatever you have defined in index.html is going to come before what you have defined in the angular-cli.json file. If you want to reorder them, include references to all css files in the angular-cli.json file.

Notice how my styles.css file is the last thing listed in the angular-cli.json file.

Edit (after rereading the original question again)

I think you need to create your own custom theme and import it.

Per Angular Material's documentation

In order to style your own components with Angular Material's tooling, the component's styles must be defined with Sass.

All you need is to create a @mixin function in the custom-component-theme.scss

See Angular Material's documentation on Theming your Own Components and their Theming Guide


问:
Populating a Cell based on the value of another cell?
I'm trying to calculate an hourly pay rate based the quantity of product being produced. Different quantities ordered will require different pay rates to produce the product.
Here is an example of what I'm trying to accomplish:

If D2(The Quantity) is between 1 and 25 Display F29( Hourly Rate 1)

If D2(The Quantity) is between 26 and 50 Display F30( Hourly Rate 2)

If D2(The Quantity) is between 51 and 100 Display F29( Hourly Rate 3)

Any help would be appreciated. Thanks.

Body:
Use this:

=INDEX(F:F,MATCH(D2,{1,26,51})+28)


问:
Javascript Unlock button in HTML and database issue
This is my html code, when ever someone clicks this question he should be able to unlock the other questions based on the ans he gave to this question

```<code><div class="section"><span>2</span>See more questions</div>
        <label for="chkYes">
                  <input name="Q2" id="Q2Yes"  type="radio" value="Yes" onclick="ShowHideDiv()" />Yes </label>
         <label for="chkNo">
                   <input name="Q2" id="Q2No"  type="radio" value="No" onclick="ShowHideDiv()" />No</label>
</code>```

The javascript Function:

```<code> <script type="text/javascript">
       function ShowHideDiv() {
           var chkYes = document.getElementById("Q2Yes");
           var dvPassport = document.getElementById("dvPassport");
           dvPassport.style.display = chkYes.checked ? "block" : "none";
    }
</script>
</code>```

The problem I am getting is when ever I save the data that the user inputs I am getting the answer for the question as "On" instead of Yes or No.
Can anyone suggest me what to do?

答:
You are getting the tag itself. You need to use:</p>

```<code>var chkYes = document.getElementById("Q2Yes").value; // "Yes"
</code>```

Body:
This is my html code, when ever someone clicks this question he should be able to unlock the other questions based on the ans he gave to this question

2See more questions

                  <input name="Q2" id="Q2Yes"  type="radio" value="Yes" onclick="ShowHideDiv()" />Yes

                   <input name="Q2" id="Q2No"  type="radio" value="No" onclick="ShowHideDiv()" />No

The javascript Function:

The problem I am getting is when ever I save the data that the user inputs I am getting the answer for the question as "On" instead of Yes or No.
Can anyone suggest me what to do?

Body:
You are getting the tag itself. You need to use:

var chkYes = document.getElementById("Q2Yes").value; // "Yes"


问:
Different behavior of the same two operations on pointers
I write this code and the output was like this B C D E

```<code>char a[5] = {'A' , 'B' , 'C' , 'D'};
char *b = a + 2;
int i = 0 ;
for(i = 0 ; i < 4 ; i ++)
{
    *b = (a[i] + 1);
    printf("%c",*b);
}
</code>```

But when I add reference like this :

```<code>char a[5] = {'A' , 'B' , 'C' , 'D'};
    char *b = &a + 2;
    int i = 0 ;
    for(i = 0 ; i < 4 ; i ++)
    {
        *b = (a[i] + 1);
        printf("%c",*b);
    }
</code>```

the output become just B.

答:
This has to do with how pointer arithmetic is done.  When you add a value to a pointer, it increments the pointer by that value times the size of the type it references.

In the expression a + 2, a has type char *, so adding 2 increases the address by 2 * sizeof(char) == 2 bytes.

Given &a + 2, &a has type char (*)[5], i.e. a pointer to an array of 5 char.  Adding 2 to this increases the address by 2 * sizeof(char [5]) == 10 bytes.  This points to a memory location past the end of the array, so dereferencing it invokes undefined behavior, which in this cases leads to the loop exiting early.

You also have an invalid assignment in the second case, as you're trying to assign a value of type char (*)[5] to a value of type char *.

Body:
I write this code and the output was like this B C D E

char a[5] = {'A' , 'B' , 'C' , 'D'};
char *b = a + 2;
int i = 0 ;
for(i = 0 ; i < 4 ; i ++)
{
    *b = (a[i] + 1);
    printf("%c",*b);
}

But when I add reference like this :

char a[5] = {'A' , 'B' , 'C' , 'D'};
    char *b = &a + 2;
    int i = 0 ;
    for(i = 0 ; i < 4 ; i ++)
    {
        *b = (a[i] + 1);
        printf("%c",*b);
    }

the output become just B.


问:
Cant get SQL results to write to file Java
The title says it all. This is my ResultSet code:

```<code>try {
    while (rs.next()) {
        int ID  = rs.getInt("ID");
        String Name = rs.getString("Name");
        String CountryCode = rs.getString("CountryCode");
        String District = rs.getString("District");
        int Population = rs.getInt("Population");

        //Display values
        try {
            writeToFile(ID, Name, CountryCode, District, Population);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

This is my writeToFile method:

```<code>public void writeToFile(int id, String name, String countryCode, String district, int population) throws IOException {
    FileWriter fw = new FileWriter("C:\\Users\\horry\\Desktop\\results.txt");
    fw.write(id + " " + name + " " + countryCode + " " + district + " " + population + "\n");
    try {
        fw.flush();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Ive tried the usual flush and close method but something is missing. Should the filewriter be declared elsewgere?

答:
Try to open file with append option

```<code> FileWriter fw = new FileWriter("C:\\Users\\horry\\Desktop\\results.txt", true);
</code>```

To add new line in any platform (e.g. linux ) use general line seperator as below

```<code>fw.write(id + " " + name + " " + countryCode + " " + district + " " + population + System.getProperty("line.separator"));
</code>```

Body:
The title says it all. This is my ResultSet code:

try {
    while (rs.next()) {
        int ID  = rs.getInt("ID");
        String Name = rs.getString("Name");
        String CountryCode = rs.getString("CountryCode");
        String District = rs.getString("District");
        int Population = rs.getInt("Population");

        //Display values
        try {
            writeToFile(ID, Name, CountryCode, District, Population);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This is my writeToFile method:

public void writeToFile(int id, String name, String countryCode, String district, int population) throws IOException {
    FileWriter fw = new FileWriter("C:\\Users\\horry\\Desktop\\results.txt");
    fw.write(id + " " + name + " " + countryCode + " " + district + " " + population + "\n");
    try {
        fw.flush();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Ive tried the usual flush and close method but something is missing. Should the filewriter be declared elsewgere?

Body:
Try to open file with append option

 FileWriter fw = new FileWriter("C:\\Users\\horry\\Desktop\\results.txt", true);

To add new line in any platform (e.g. linux ) use general line seperator as below

fw.write(id + " " + name + " " + countryCode + " " + district + " " + population + System.getProperty("line.separator"));


问:
C++ Pointer to OpenCV GpuMat
I am using OpenCV 3.0 with VS2012 C++/CLI on a Win 8.1 64 bit machine.

I am wondering what the proper way is to create a C++ pointer to a Gpumat.

Currently, I define some pointers, like:

```<code>cuda::GpuMat *d_gpuLoadFrame;
cuda::GpuMat *d_gpuLoadFrameClone;
cuda::GpuMat *d_gpuAnalysisFrame;
cuda::GpuMat *d_gpuGrayFrame;
cuda::GpuMat *d_gpuMaskFrame;
cuda::GpuMat *d_gpuFalseMaskFrame;
</code>```

Then I allocate the pointers themselves like:

```<code>d_gpuLoadFrame = new cuda::GpuMat();
d_gpuLoadFrameClone = new cuda::GpuMat();
d_gpuAnalysisFrame = new cuda::GpuMat();
d_gpuGrayFrame = new cuda::GpuMat();
d_gpuMaskFrame = new cuda::GpuMat();
d_gpuFalseMaskFrame = new cuda::GpuMat();
d_gputFrame = new cuda::GpuMat();
</code>```

I am seeing some weird behavior that is making me think this might be wrong.  For examples, I upload a standard Mat into some of these and clone them in various ways and it looks like the C++ pointer is being lost.

Do I need to do something different to keep track of the Gpumats so that they are not destroyed as I move from function to function?

答:
There is no need for providing pointers in the manner you have shown. A GpuMat file can just be passed to a function simply by writing the name in the actual parameters of the calling function. While at the function side it can be accessed using reference shown as under:

   GpuMat abc;
    foo(abc);
    //at the function definition
    void foo(GpuMat& abc) { ... }

Title: C++ Pointer to OpenCV GpuMat

Body:
I am using OpenCV 3.0 with VS2012 C++/CLI on a Win 8.1 64 bit machine.

I am wondering what the proper way is to create a C++ pointer to a Gpumat.

Currently, I define some pointers, like:

cuda::GpuMat *d_gpuLoadFrame;
cuda::GpuMat *d_gpuLoadFrameClone;
cuda::GpuMat *d_gpuAnalysisFrame;
cuda::GpuMat *d_gpuGrayFrame;
cuda::GpuMat *d_gpuMaskFrame;
cuda::GpuMat *d_gpuFalseMaskFrame;

Then I allocate the pointers themselves like:

d_gpuLoadFrame = new cuda::GpuMat();
d_gpuLoadFrameClone = new cuda::GpuMat();
d_gpuAnalysisFrame = new cuda::GpuMat();
d_gpuGrayFrame = new cuda::GpuMat();
d_gpuMaskFrame = new cuda::GpuMat();
d_gpuFalseMaskFrame = new cuda::GpuMat();
d_gputFrame = new cuda::GpuMat();

I am seeing some weird behavior that is making me think this might be wrong.  For examples, I upload a standard Mat into some of these and clone them in various ways and it looks like the C++ pointer is being lost.

Do I need to do something different to keep track of the Gpumats so that they are not destroyed as I move from function to function?


问:
rxImport fails on large dataset
I've been trying unsuccessfully the past two days to convert a large CSV (9 gigs) into XDF format using the RxImport function.

The process seems to start off well with R server reading in the data chunk by chunk but after a few minutes it slows to a crawl and then fails completely after around 6 hours with Windows stopping the server saying its run out of RAM.

The code I'm using is as follows:

```<code>pd_in_file <- RxTextData("cca_pd_entity.csv", delimiter = ",") #file to import
pd_out_file <- file.path("cca_pd_entity.xdf") #desired output file
pd_data <- rxImport(inData = pd_in_file, outFile = pd_out_file,
stringsAsFactors = TRUE, overwrite = TRUE)
</code>```

I'm running Microsoft R Server, version 9.0.1. on a Windows 7 machine with 16gig of RAM.

Thanks

答: Its been solved using Hong Ooi's recommendation to set the colInfo in the rxTextData. I'm not sure why it made such a big difference but it converted the entire 9gig dataset in less than 2 minutes when it completely failed to import after several hours before. </p>

Title: rxImport fails on large dataset

Body:
I've been trying unsuccessfully the past two days to convert a large CSV (9 gigs) into XDF format using the RxImport function.

The process seems to start off well with R server reading in the data chunk by chunk but after a few minutes it slows to a crawl and then fails completely after around 6 hours with Windows stopping the server saying its run out of RAM.

The code I'm using is as follows:

pd_in_file <- RxTextData("cca_pd_entity.csv", delimiter = ",") #file to import
pd_out_file <- file.path("cca_pd_entity.xdf") #desired output file
pd_data <- rxImport(inData = pd_in_file, outFile = pd_out_file,
stringsAsFactors = TRUE, overwrite = TRUE)

I'm running Microsoft R Server, version 9.0.1. on a Windows 7 machine with 16gig of RAM.

Thanks