问:
Identify Process using AMD-V or Intel VT-X in Windows 10 1903
I want to positively identify a process that is blocking AMD-V.

Background:

Despite my efforts to resist, Windows 10 decided it was time to upgrade to 1903 and this has left VirtualBox 6.0 inoperable.

```<code>(VERR_NEM_MISSING_KERNEL_API).
AMD-V is not available (VERR_SVM_NO_SVM).
</code>```

I know that is somewhat misleading because:

It worked before.

It is still enabled in the BIOS (I double-checked).

and

I have checked that Hyper-V is indeed still not enabled (Windows 10 Pro). A previous update through me for a loop when it magically turned on, but this time, it doesn't seem to be the culprit.

I don't think it's a zero-day issue because the update has been out for a while. Just for giggles,  I decided to press on forward and install all available updates. Still no joy.

I'm starting to suspect that something is using the hardware virtualization and locking the resource. But what? And, how to find out?

Is there a way to identify a running process that is using AMD-V? (Phenom  II X6 1055T)

No joy from Googling - I only found heaps of articles repeating the steps above.

Any help would be greatly appreciated. This is probably my last stop before I revert the update.

Thanks!

答:
What helps me:

I installed updates to Windows 10.

I downloaded last Virtual Box (6.0.16)

Turn Windows features on or off

Disable Hyper V, Windows Hypervisor Platform (may be I shouldn`t and last versions are enough.)

Body:
I want to positively identify a process that is blocking AMD-V.

Background:

Despite my efforts to resist, Windows 10 decided it was time to upgrade to 1903 and this has left VirtualBox 6.0 inoperable.

(VERR_NEM_MISSING_KERNEL_API).
AMD-V is not available (VERR_SVM_NO_SVM).

I know that is somewhat misleading because:

It worked before.

It is still enabled in the BIOS (I double-checked).

and

I have checked that Hyper-V is indeed still not enabled (Windows 10 Pro). A previous update through me for a loop when it magically turned on, but this time, it doesn't seem to be the culprit.

I don't think it's a zero-day issue because the update has been out for a while. Just for giggles,  I decided to press on forward and install all available updates. Still no joy.

I'm starting to suspect that something is using the hardware virtualization and locking the resource. But what? And, how to find out?

Is there a way to identify a running process that is using AMD-V? (Phenom  II X6 1055T)

No joy from Googling - I only found heaps of articles repeating the steps above.

Any help would be greatly appreciated. This is probably my last stop before I revert the update.

Thanks!


来源: stackexchange

问:
'tensorflow' has no attribute 'Session'
I am trying to convert a Tensor to a numpy array.
The tensor i have has a shape as below

```<code>LastDenseLayer.output.shape
TensorShape([None, 128])
</code>```

When i am running the code as below,

```<code>with tf.Session() as sess:
    LastLayer = LastDenseLayer.output.eval()
</code>```

getting the below error

module 'tensorflow' has no attribute 'Session'

I am running Keras model and trying to get the values of a specific layer out of that.

Unable to understand that is wrong here.

Regards
Sachin

答:
It's recommended to update your code to meet Tensorflow 2.0 requirements. As a quick solution you can use tf.compat.v1.Session() instead of tf.Session():

```<code>with tf.compat.v1.Session() as sess:
    LastLayer = LastDenseLayer.output.eval()
</code>```

ContentLicense: CC BY-SA 4.0

Title: 'tensorflow' has no attribute 'Session'

Body:
I am trying to convert a Tensor to a numpy array.
The tensor i have has a shape as below

LastDenseLayer.output.shape
TensorShape([None, 128])

When i am running the code as below,

with tf.Session() as sess:
    LastLayer = LastDenseLayer.output.eval()

getting the below error

module 'tensorflow' has no attribute 'Session'

I am running Keras model and trying to get the values of a specific layer out of that.

Unable to understand that is wrong here.

Regards
Sachin

Body:
It's recommended to update your code to meet Tensorflow 2.0 requirements. As a quick solution you can use tf.compat.v1.Session() instead of tf.Session():

with tf.compat.v1.Session() as sess:
    LastLayer = LastDenseLayer.output.eval()


问:
Finding path obstacles in a 2D image
what approach would you recommend for finding obstacles in a 2D image?

Here are some key points I came up with till now:

I doubt I can use object recognition based on "database of obstacles" search, since I don't know what might the obstruction look like.
I assume color recognition might be problematic if the path does not differ a lot from the object itself.

Possibly, adding one more camera and computing a 3D image (like a Kinect does) would work, but that would not run as smooth as I require.

To illustrate the problem; robot can ride either left or right side of the pavement. In the following picture, left side is the correct choice:

答:
If you know what the path looks like, this is largely a classification problem. Acquire a bunch of images of path at different distances, illumination, etc. and manually label the ground in each image. Use this labeled data to train a classifier that classifies each pixel as either "road" or "not road." Depending upon the texture of the road, this could be as simple as classifying each pixels' RGB (or HSV) values or using OpenCv's built-in histogram back-projection (i.e. cv::CalcBackProjectPatch()).

I suggest beginning with manual thresholds, moving to histogram-based matching, and only using a full-fledged machine learning classifier (such as a Naive Bayes Classifier or a SVM) if the simpler techniques fail. Once the entire image is classified, all pixels that are identified as "not road" are obstacles. By classifying the road instead of the obstacles, we completely avoided building a "database of objects".

Somewhat out of the scope of the question, the easiest solution is to add additional sensors ("throw more hardware at the problem!") and directly measure the three-dimensional position of obstacles. In order of preference:

Microsoft Kinect: Cheap, easy, and effective. Due to ambient IR light, it only works indoors.

Scanning Laser Rangefinder: Extremely accurate, easy to setup, and works outside. Also very expensive (~$1200-10,000 depending upon maximum range and sample rate).

Stereo Camera: Not as good as a Kinect, but it works outside. If you cannot afford a pre-made stereo camera (~$1800), you can make a decent custom stereo camera using USB webcams.

Note that professional stereo vision cameras can be very fast by using custom hardware (Stereo On-Chip, STOC). Software-based stereo is also reasonably fast (10-20 Hz) on a modern computer.

ContentLicense: CC BY-SA 3.0

Title: Finding path obstacles in a 2D image


问:
iOS Safari VoiceOver - How to read dynamic content?
After executing following code (https://output.jsbin.com/refezujebi):

Actual result:
Swipe right from "first title" will cause VoiceOver to read "second title".

Expected result:
Swipe right from "first title" will cause VoiceOver to read "loaded".

Note: dynamic div is initially empty. Is it possible to get the expected behavior?

first title

second title

```

答:
I have found a solution.
In order to make voice-over detect changes in dynamic content you need to delete it and insert it again.
Here's snippet demonstrating what do I mean.

const button = $('button')
button.on('click', change)

function change(){
 const label = $('#label')
  label.empty().text('new label'); // remove the node and then reinserts it with new label text
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="label">
 some label
</h1>

<button onclick="change()">
 TEST
</button></code>```

Here's solution to OP's problem.

first title

second title

```

Body:
I have found a solution.
In order to make voice-over detect changes in dynamic content you need to delete it and insert it again.
Here's snippet demonstrating what do I mean.

const button = $('button')
button.on('click', change)

function change(){
 const label = $('#label')
  label.empty().text('new label'); // remove the node and then reinserts it with new label text
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="label">
 some label
</h1>

<button onclick="change()">
 TEST
</button>

Here's solution to OP's problem.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <body>
    <h2>first title</h2>
    <div id="dynamic"></div>
    <h2>second title</h2>
    <script>
      setTimeout(() =>{
        const element = $('#dynamic');
        element.empty();
        element.html('loaded');
      }, 2000)
    </script>
  </body>
</html>


问:
CORS Issue - Angular 8 - NodeJS & ExpressJS
I've tried a few different solutions from other threads and suspect I'm missing something small here.

I have an AngularJS 8 application, running on Node 10 with ExpressJS. Having some CORS issues when trying to access Google's People API.

Access to XMLHttpRequest at 'https://developers.google.com/people/api/rest/v1/people.connections' from origin 'http://app.x.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

My frontend code looks like:

```<code>    return this.httpClient.get(this.API_URL, {
      headers: new HttpHeaders({
        Authorization: `Bearer ${authtoken}`,
        'Access-Control-Allow-Origin': 'http://localhost:4200',
        'Access-Control-Allow-Credentials': 'true',
      })
    });
  }
</code>```

My server side code:

```<code>
let express = require('express'),
  path = require('path'),
  cors = require('cors');
// Connecting mongoDB
var compression = require('compression')
var session = require("express-session");

let app = express();
app.use(session({
  secret: '#######################',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));
app.use(compression())
app.use(cors());

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

/*var corsOptions = {
  origin: '*',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
*/

app.use(express.static(path.join(__dirname, 'dist/###')));
app.use('/*', express.static(path.join(__dirname, 'dist/##')));
// Create port
const port = 8080;
const server = app.listen(port, () => {
  console.log('Connected to port ' + port)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});

app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  {
    res.status(err.statusCode).send(err.message);
  }

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  if (!err.statusCode) err.statusCode = 500;
  {
    res.status(err.statusCode).send(err.message);
  }

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});

</code>```

As you can see, I've tried a couple of different approaches. Would appreciate any suggestions.

Thank You

答:
Fixed the issue in another way. Using the Gapi library (javascript: https://github.com/google/google-api-javascript-client/blob/master/docs/reference.md ) and its Auth, I was able to login, get the JWT and use that as a credential.

```<code>    const googleUser = await googleAuth.signIn();

    const token = googleUser.getAuthResponse().id_token;

    const credential = firebase.auth.GoogleAuthProvider.credential(token);
    await firebase.auth().signInAndRetrieveDataWithCredential(credential);

    return googleUser;
</code>```

Using that credential login to firebase. All the while, being loggedin to Google Api's thanks to Gapi's Javascript Library. You can use a gapi instance then to request resources and api's depending on your scope of course.

```<code> const contacts = await gapi.client.request({
        'path': 'https://people.googleapis.com/v1/people/me/connections?personFields=email_addresses,names&pageToken=CAAQwo2YuIUuGgYKAghkEAI&pageSize=2000',

      })
</code>```

No CORS issues, no fuss. Just posting incase it helps someone else save some time.

Body:
I've tried a few different solutions from other threads and suspect I'm missing something small here.

I have an AngularJS 8 application, running on Node 10 with ExpressJS. Having some CORS issues when trying to access Google's People API.

Access to XMLHttpRequest at 'https://developers.google.com/people/api/rest/v1/people.connections' from origin 'http://app.x.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

My frontend code looks like:

    return this.httpClient.get(this.API_URL, {
      headers: new HttpHeaders({
        Authorization: `Bearer ${authtoken}`,
        'Access-Control-Allow-Origin': 'http://localhost:4200',
        'Access-Control-Allow-Credentials': 'true',
      })
    });
  }

My server side code:

let express = require('express'),
  path = require('path'),
  cors = require('cors');
// Connecting mongoDB
var compression = require('compression')
var session = require("express-session");

let app = express();
app.use(session({
  secret: '#######################',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));
app.use(compression())
app.use(cors());

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

/*var corsOptions = {
  origin: '*',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
*/

app.use(express.static(path.join(__dirname, 'dist/###')));
app.use('/*', express.static(path.join(__dirname, 'dist/##')));
// Create port
const port = 8080;
const server = app.listen(port, () => {
  console.log('Connected to port ' + port)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});

app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  {
    res.status(err.statusCode).send(err.message);
  }

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  if (!err.statusCode) err.statusCode = 500;
  {
    res.status(err.statusCode).send(err.message);
  }

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});

As you can see, I've tried a couple of different approaches. Would appreciate any suggestions.

Thank You

Body:
Fixed the issue in another way. Using the Gapi library (javascript: https://github.com/google/google-api-javascript-client/blob/master/docs/reference.md ) and its Auth, I was able to login, get the JWT and use that as a credential.

    const googleUser = await googleAuth.signIn();

    const token = googleUser.getAuthResponse().id_token;

    const credential = firebase.auth.GoogleAuthProvider.credential(token);
    await firebase.auth().signInAndRetrieveDataWithCredential(credential);

    return googleUser;

Using that credential login to firebase. All the while, being loggedin to Google Api's thanks to Gapi's Javascript Library. You can use a gapi instance then to request resources and api's depending on your scope of course.

 const contacts = await gapi.client.request({
        'path': 'https://people.googleapis.com/v1/people/me/connections?personFields=email_addresses,names&pageToken=CAAQwo2YuIUuGgYKAghkEAI&pageSize=2000',

      })

No CORS issues, no fuss. Just posting incase it helps someone else save some time.


问:
VBA Extract data from specific column on another sheet
I have 2 sheets which I extract from the system. For sheet1(Data) contain multiple column and all the data inside. For sheet2(Get) I have 2 column, as per below. With reference column no 2 (ID) on sheet2(Get), I want to search this value in the sheet1(Data) then extract specific column value. I try to search online for example code and found this piece of code which extract all column value. But I only want to extract column with highlighted with yellow then extract this value into sheet2(Get). Can help me to modified this code?

Note: For sheet2(Get), all the data on both column A and B already prefilled so I would like to change Worksheet_SelectionChange into a normal sub then run this sub using macro. Possible?

```<code>Column C (Get sheet) should extract from Column B (Data sheet)
Column D (Get sheet) should extract from Column M (Data sheet)
Column E (Get sheet) should extract from Column J (Data sheet)
Column F (Get sheet) should extract from Column L (Data sheet)
Column G (Get sheet) should extract from Column C (Data sheet)
Column H (Get sheet) should extract from Column G (Data sheet)
</code>```

sheet2(Get)

sheet1(Data)

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim k As Integer, i As Long, Str As Range
    'row number
    For i = 3 To Sheets("GetData").Range("a65536").End(3).Row
        Set Str = Sheets("Data").Range("a:a").Find(Cells(i, 1).Value, , xlValues, xlWhole)
        If Not Str Is Nothing Then
            'column number
            For k = 1 To 14
                If k > 1 Then Sheets("GetData").Cells(i, k).Value = Sheets("Data").Cells(Str.Row, k).Value
            Next k
        Else
            For k = 2 To 14

                Sheets("GetData").Cells(i, k).Value = "Null"
            Next k

        End If
    Next i
End Sub
</code>```

答:
Once you have the row you can copy like this:</p>

```<code>Dim col As Long
'...
'...
col = 3
For Each e In Array(2, 3, 7, 10) 'columns to fetch
    Sheets("GetData").Cells(i, col).Value = Str.EntireRow.Cells(e).Value
    col = col + 1
Next
'...
'...
</code>```

Body:
I have 2 sheets which I extract from the system. For sheet1(Data) contain multiple column and all the data inside. For sheet2(Get) I have 2 column, as per below. With reference column no 2 (ID) on sheet2(Get), I want to search this value in the sheet1(Data) then extract specific column value. I try to search online for example code and found this piece of code which extract all column value. But I only want to extract column with highlighted with yellow then extract this value into sheet2(Get). Can help me to modified this code?

Note: For sheet2(Get), all the data on both column A and B already prefilled so I would like to change Worksheet_SelectionChange into a normal sub then run this sub using macro. Possible?

Column C (Get sheet) should extract from Column B (Data sheet)
Column D (Get sheet) should extract from Column M (Data sheet)
Column E (Get sheet) should extract from Column J (Data sheet)
Column F (Get sheet) should extract from Column L (Data sheet)
Column G (Get sheet) should extract from Column C (Data sheet)
Column H (Get sheet) should extract from Column G (Data sheet)

sheet2(Get)

sheet1(Data)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim k As Integer, i As Long, Str As Range
    'row number
    For i = 3 To Sheets("GetData").Range("a65536").End(3).Row
        Set Str = Sheets("Data").Range("a:a").Find(Cells(i, 1).Value, , xlValues, xlWhole)
        If Not Str Is Nothing Then
            'column number
            For k = 1 To 14
                If k > 1 Then Sheets("GetData").Cells(i, k).Value = Sheets("Data").Cells(Str.Row, k).Value
            Next k
        Else
            For k = 2 To 14

                Sheets("GetData").Cells(i, k).Value = "Null"
            Next k

        End If
    Next i
End Sub

Body:
Once you have the row you can copy like this:

Dim col As Long
'...
'...
col = 3
For Each e In Array(2, 3, 7, 10) 'columns to fetch
    Sheets("GetData").Cells(i, col).Value = Str.EntireRow.Cells(e).Value
    col = col + 1
Next
'...
'...


问:
Listview TwoWay Binding With ObservableCollection
:::::::::: ObservableCollection ::::::::::

```<code>    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );
</code>```

:::::::::: InitializeFriends ::::::::::

```<code>        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }
</code>```

:::::::::: Friend ::::::::::

```<code>    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }
</code>```

:::::::::: ListView ::::::::::

```<code>        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</code>```

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG

答: Your Friend class needs to implement the INotifyPropertyChanged interface, so that WPF notifies when a change has been made to that property.

Body:
:::::::::: ObservableCollection ::::::::::

    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );

:::::::::: InitializeFriends ::::::::::

        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }

:::::::::: Friend ::::::::::

    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }

:::::::::: ListView ::::::::::

        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG


问:
arithmatic operators as a function input (C++)
Let's say I have a function

```<code>#include <iostream>
int do_math (num_1, num_2, "*"){
....
}
</code>```

Where the code takes the inputs and applies the operator in the function to obtain the result of the calculation.

I'm not sure how to incorporate the arithmetic operator in the function to do the calculation. I was thinking of using the operator value from the ASCII table, but I was hoping maybe I can somehow incorporate istringstream method to do that. Any suggestions?

答:
You can use lambda for any arbitrary operation.

```<code>#include <iostream>
#include <cmath>

template<typename T, typename F>
auto do_math(T a, T b, F&& op)
{
    return op(a, b);
}

int main() {
    auto ans = do_math(5, 4, [](int x, int y) -> int { return x+y; });
    std::cout << ans << std::endl;
    auto ans2 = do_math(5, 4, [](int x, int y) -> int { return std::pow(x, y); });
    std::cout << ans2 << std::endl;
    return 0;
}
</code>```

Body:
Let's say I have a function

#include <iostream>
int do_math (num_1, num_2, "*"){
....
}

Where the code takes the inputs and applies the operator in the function to obtain the result of the calculation.

I'm not sure how to incorporate the arithmetic operator in the function to do the calculation. I was thinking of using the operator value from the ASCII table, but I was hoping maybe I can somehow incorporate istringstream method to do that. Any suggestions?

Body:
You can use lambda for any arbitrary operation.

#include <iostream>
#include <cmath>

template<typename T, typename F>
auto do_math(T a, T b, F&& op)
{
    return op(a, b);
}

int main() {
    auto ans = do_math(5, 4, [](int x, int y) -> int { return x+y; });
    std::cout << ans << std::endl;
    auto ans2 = do_math(5, 4, [](int x, int y) -> int { return std::pow(x, y); });
    std::cout << ans2 << std::endl;
    return 0;
}


问:
MEAN Stack protect layouts routes
I'm Working with MEAN Stack , And i have 3 layouts and i want to protect every layout routes to prevent other layouts to access it

```<code>const routes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full'
},
{
    path: 'main-admin',
    component: MainAdminLayoutComponent,
    children: [
        {
            path: '',
            loadChildren: () =>
                import('./layouts/main-admin-layout/main-admin-layout.module').then(m => m.MainAdminLayoutModule)
        }
    ]
},
{
    path: 'main-admin',
    component: MainAdminLayoutComponent,
    loadChildren: () =>
        import('./main-admin-components/main-admin.component.module').then(m => m.MainAdminComponentModule)
},
{
    path: '',
    component: AdminLayoutComponent,
    children: [
        {
            path: '',
            loadChildren: () =>
                import('./layouts/admin-layout/admin-layout.module').then(m => m.AdminLayoutModule)
        }
    ]
},
{
    path: '',
    component: AdminLayoutComponent,
    loadChildren: () =>
        import('./components/component.module').then(m => m.ComponentModule)
},
{
    path: 'user',
    component: SiteLayoutComponent,
    children: [
        {
            path: '',
            loadChildren: () =>
                import('./layouts/site-layout/site-layout.module').then(m => m.SiteLayoutModule)
        }
    ]
},
{
    path: '',
    component: UserLayoutComponent,
    children: [
        {
            path: 'account',
            loadChildren: () =>
                import('./layouts/user-layout/user-layout.module').then(m => m.UserLayoutModule)
        }
    ]
},
{
    path: '**',
    component: NotFoundComponent
}
</code>```

];

Each route i want to protect ... Let's say i just a user and if i want to access admin routes redirect me to my dashboard

Any help please ??!!

答:
The thing that you are trying to achieve over here is, users will have access to visit only particular components. In case if they are trying to visit a component for which they are not having access, they must be redirected to some other component.

This can be achieved by a feature called Angular Route Resolvers;. Usiing which you will run a piece of code before navigating ot that component and decide whether it can be navigated or not. You can find a detail implementation of route resolvers with example over here - https://dzone.com/articles/understanding-angular-route-resolvers-by-example

Title: MEAN Stack protect layouts routes

Body:
I'm Working with MEAN Stack , And i have 3 layouts and i want to protect every layout routes to prevent other layouts to access it

const routes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full'
},
{
    path: 'main-admin',
    component: MainAdminLayoutComponent,
    children: [
        {
            path: '',
            loadChildren: () =>
                import('./layouts/main-admin-layout/main-admin-layout.module').then(m => m.MainAdminLayoutModule)
        }
    ]
},
{
    path: 'main-admin',
    component: MainAdminLayoutComponent,
    loadChildren: () =>
        import('./main-admin-components/main-admin.component.module').then(m => m.MainAdminComponentModule)
},
{
    path: '',
    component: AdminLayoutComponent,
    children: [
        {
            path: '',
            loadChildren: () =>
                import('./layouts/admin-layout/admin-layout.module').then(m => m.AdminLayoutModule)
        }
    ]
},
{
    path: '',
    component: AdminLayoutComponent,
    loadChildren: () =>
        import('./components/component.module').then(m => m.ComponentModule)
},
{
    path: 'user',
    component: SiteLayoutComponent,
    children: [
        {
            path: '',
            loadChildren: () =>
                import('./layouts/site-layout/site-layout.module').then(m => m.SiteLayoutModule)
        }
    ]
},
{
    path: '',
    component: UserLayoutComponent,
    children: [
        {
            path: 'account',
            loadChildren: () =>
                import('./layouts/user-layout/user-layout.module').then(m => m.UserLayoutModule)
        }
    ]
},
{
    path: '**',
    component: NotFoundComponent
}

];

Each route i want to protect ... Let's say i just a user and if i want to access admin routes redirect me to my dashboard

Any help please ??!!


问:
Openshift_control_plane : Report control plane errors
I'm trying to install Openshift Origin with Ansible. I got an issue when execute deploy_cluster.yml and the error is :

```<code>TASK [openshift_control_plane : Report control plane errors] ***********************************************************************************************************
fatal: [masterserver.srv.com]: FAILED! => {"changed": false, "msg": "Control plane pods didn't come up"}

NO MORE HOSTS LEFT *****************************************************************************************************************************************************

PLAY RECAP *************************************************************************************************************************************************************
localhost                  : ok=11   changed=0    unreachable=0    failed=0    skipped=5    rescued=0    ignored=0
masterserver.srv.com       : ok=295  changed=44   unreachable=0    failed=1    skipped=233  rescued=0    ignored=4
nodeserver.srv.com         : ok=103  changed=16   unreachable=0    failed=0    skipped=88   rescued=0    ignored=0

INSTALLER STATUS *******************************************************************************************************************************************************
Initialization              : Complete (0:02:49)
Health Check                : Complete (0:00:36)
Node Bootstrap Preparation  : Complete (0:09:55)
etcd Install                : Complete (0:02:05)
Master Install              : In Progress (0:42:42)
        This phase can be restarted by running: playbooks/openshift-master/config.yml

Failure summary:

  1. Hosts:    masterserver.srv.com
     Play:     Configure masters
     Task:     Report control plane errors
     Message:  Control plane pods didn't come up
</code>```

Description about my environment :

Ansible version

```<code>[root@masterserver ~]# ansible --version
ansible 2.9.2`enter code here`
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
</code>```

OS Version (Master - Client same version)

```<code>[root@masterserver ~]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
</code>```

Docker Version

```<code>[root@masterserver ~]# docker version
Client:
 Version:         1.13.1
 API version:     1.26
 Package version: docker-1.13.1-103.git7f2769b.el7.centos.x86_64
 Go version:      go1.10.3
 Git commit:      7f2769b/1.13.1
 Built:           Sun Sep 15 14:06:47 2019
 OS/Arch:         linux/amd64

Server:
 Version:         1.13.1
 API version:     1.26 (minimum version 1.12)
 Package version: docker-1.13.1-103.git7f2769b.el7.centos.x86_64
 Go version:      go1.10.3
 Git commit:      7f2769b/1.13.1
 Built:           Sun Sep 15 14:06:47 2019
 OS/Arch:         linux/amd64
 Experimental:    false
</code>```

Steps that I did :

ansible-playbook openshift-ansible/playbooks/prerequisites.yml (Success)

ansible-playbook openshift-ansible/playbooks/deploy_cluster.yml

Additional :

```<code>[root@masterserver ~]# cat /etc/ansible/hosts
[OSEv3:children]
masters
nodes
etcd

[OSEv3:vars]
ansible_ssh_user=origin
ansible_become=true
openshift_deployment_type=origin
openshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider'}]
openshift_master_default_subdomain=apps-masterserver.srv.com
openshift_disable_check=disk_availability,docker_storage,memory_availability,docker_image_availability
openshift_master_api_port=8443
openshift_master_console_port=8443
osm_etcd_image=registry.access.redhat.com/rhel7/etcd:3.2.22

[masters]
masterserver.srv.com

[etcd]
masterserver.srv.com

[nodes]
masterserver.srv.com openshift_node_group_name='node-config-master-infra'
nodeserver.srv.com openshift_node_group_name='node-config-compute'
```

[root@masterserver ~]# hostname
masterserver.srv.com

[root@masterserver ~]# oc get nodes
The connection to the server masterserver.srv.com:8443 was refused - did you specify the right host or port?

[root@masterserver ~]# netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:8444            0.0.0.0:*               LISTEN      1700/openshift
tcp        0      0 127.0.0.1:44642         0.0.0.0:*               LISTEN      1407/hyperkube
tcp        0      0 192.168.43.50:2379      0.0.0.0:*               LISTEN      1647/etcd
tcp        0      0 192.168.43.50:2380      0.0.0.0:*               LISTEN      1647/etcd
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd
tcp        0      0 172.17.0.1:53           0.0.0.0:*               LISTEN      1024/dnsmasq
tcp        0      0 192.168.43.50:53        0.0.0.0:*               LISTEN      1024/dnsmasq
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1029/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1166/master
tcp6       0      0 :::10250                :::*                    LISTEN      1407/hyperkube
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd
tcp6       0      0 fe80::a00:27ff:fee8::53 :::*                    LISTEN      1024/dnsmasq
tcp6       0      0 :::22                   :::*                    LISTEN      1029/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1166/master

[root@masterserver ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.43.51   nodeserver.srv.com
192.168.43.50   masterserver.srv.com
```

<p>Control plane pods didn't come up so the installation got stuck. This is the one of error process when ansible was run :</p>

```[WARNING]: Module invocation had junk after the JSON data: Error in atexit._run_exitfuncs: Traceback (most recent call last):   File "/usr/lib64/python2.7/atexit.py",
line 24, in _run_exitfuncs     func(*targs, **kargs)   File "/tmp/ansible_oc_obj_payload_h6RqDy/ansible_oc_obj_payload.zip/ansible/modules/oc_obj.py", line 1257, in
cleanup AttributeError: 'NoneType' object has no attribute 'path' Error in sys.exitfunc: Traceback (most recent call last):   File "/usr/lib64/python2.7/atexit.py",
line 24, in _run_exitfuncs     func(*targs, **kargs)   File "/tmp/ansible_oc_obj_payload_h6RqDy/ansible_oc_obj_payload.zip/ansible/modules/oc_obj.py", line 1257, in
cleanup AttributeError: 'NoneType' object has no attribute 'path'
```

Anyone can help me to solve this issue ? Thanks.

答:
Solved ! Move my environment to higher specifications. I saw some logs show that the resources I use before 1vcpu and RAM 2GB (Master + Infra1, Compute 1) => Recording NodeHasSufficientResources in /var/log/messages.

Currently, I use 2vcpu and RAM 8GB (Master + Infra 1, Compute 1) and works well !

Body:
I'm trying to install Openshift Origin with Ansible. I got an issue when execute deploy_cluster.yml and the error is :

TASK [openshift_control_plane : Report control plane errors] ***********************************************************************************************************
fatal: [masterserver.srv.com]: FAILED! => {"changed": false, "msg": "Control plane pods didn't come up"}

NO MORE HOSTS LEFT *****************************************************************************************************************************************************

PLAY RECAP *************************************************************************************************************************************************************
localhost                  : ok=11   changed=0    unreachable=0    failed=0    skipped=5    rescued=0    ignored=0
masterserver.srv.com       : ok=295  changed=44   unreachable=0    failed=1    skipped=233  rescued=0    ignored=4
nodeserver.srv.com         : ok=103  changed=16   unreachable=0    failed=0    skipped=88   rescued=0    ignored=0

INSTALLER STATUS *******************************************************************************************************************************************************
Initialization              : Complete (0:02:49)
Health Check                : Complete (0:00:36)
Node Bootstrap Preparation  : Complete (0:09:55)
etcd Install                : Complete (0:02:05)
Master Install              : In Progress (0:42:42)
        This phase can be restarted by running: playbooks/openshift-master/config.yml

Failure summary:

  1. Hosts:    masterserver.srv.com
     Play:     Configure masters
     Task:     Report control plane errors
     Message:  Control plane pods didn't come up

Description about my environment :

Ansible version

[root@masterserver ~]# ansible --version
ansible 2.9.2`enter code here`
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

OS Version (Master - Client same version)

[root@masterserver ~]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

Docker Version

[root@masterserver ~]# docker version
Client:
 Version:         1.13.1
 API version:     1.26
 Package version: docker-1.13.1-103.git7f2769b.el7.centos.x86_64
 Go version:      go1.10.3
 Git commit:      7f2769b/1.13.1
 Built:           Sun Sep 15 14:06:47 2019
 OS/Arch:         linux/amd64

Server:
 Version:         1.13.1
 API version:     1.26 (minimum version 1.12)
 Package version: docker-1.13.1-103.git7f2769b.el7.centos.x86_64
 Go version:      go1.10.3
 Git commit:      7f2769b/1.13.1
 Built:           Sun Sep 15 14:06:47 2019
 OS/Arch:         linux/amd64
 Experimental:    false

Steps that I did :

ansible-playbook openshift-ansible/playbooks/prerequisites.yml (Success)

ansible-playbook openshift-ansible/playbooks/deploy_cluster.yml

Additional :

[root@masterserver ~]# cat /etc/ansible/hosts
[OSEv3:children]
masters
nodes
etcd

[OSEv3:vars]
ansible_ssh_user=origin
ansible_become=true
openshift_deployment_type=origin
openshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider'}]
openshift_master_default_subdomain=apps-masterserver.srv.com
openshift_disable_check=disk_availability,docker_storage,memory_availability,docker_image_availability
openshift_master_api_port=8443
openshift_master_console_port=8443
osm_etcd_image=registry.access.redhat.com/rhel7/etcd:3.2.22

[masters]
masterserver.srv.com

[etcd]
masterserver.srv.com

[nodes]
masterserver.srv.com openshift_node_group_name='node-config-master-infra'
nodeserver.srv.com openshift_node_group_name='node-config-compute'
```

[root@masterserver ~]# hostname
masterserver.srv.com

[root@masterserver ~]# oc get nodes
The connection to the server masterserver.srv.com:8443 was refused - did you specify the right host or port?

[root@masterserver ~]# netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:8444            0.0.0.0:*               LISTEN      1700/openshift
tcp        0      0 127.0.0.1:44642         0.0.0.0:*               LISTEN      1407/hyperkube
tcp        0      0 192.168.43.50:2379      0.0.0.0:*               LISTEN      1647/etcd
tcp        0      0 192.168.43.50:2380      0.0.0.0:*               LISTEN      1647/etcd
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd
tcp        0      0 172.17.0.1:53           0.0.0.0:*               LISTEN      1024/dnsmasq
tcp        0      0 192.168.43.50:53        0.0.0.0:*               LISTEN      1024/dnsmasq
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1029/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1166/master
tcp6       0      0 :::10250                :::*                    LISTEN      1407/hyperkube
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd
tcp6       0      0 fe80::a00:27ff:fee8::53 :::*                    LISTEN      1024/dnsmasq
tcp6       0      0 :::22                   :::*                    LISTEN      1029/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1166/master

[root@masterserver ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.43.51   nodeserver.srv.com
192.168.43.50   masterserver.srv.com

Control plane pods didn't come up so the installation got stuck. This is the one of error process when ansible was run :

[WARNING]: Module invocation had junk after the JSON data: Error in atexit._run_exitfuncs: Traceback (most recent call last):   File "/usr/lib64/python2.7/atexit.py",
line 24, in _run_exitfuncs     func(*targs, **kargs)   File "/tmp/ansible_oc_obj_payload_h6RqDy/ansible_oc_obj_payload.zip/ansible/modules/oc_obj.py", line 1257, in
cleanup AttributeError: 'NoneType' object has no attribute 'path' Error in sys.exitfunc: Traceback (most recent call last):   File "/usr/lib64/python2.7/atexit.py",
line 24, in _run_exitfuncs     func(*targs, **kargs)   File "/tmp/ansible_oc_obj_payload_h6RqDy/ansible_oc_obj_payload.zip/ansible/modules/oc_obj.py", line 1257, in
cleanup AttributeError: 'NoneType' object has no attribute 'path'

Anyone can help me to solve this issue ? Thanks.


问:
Nothing happened when tap blank space of the list item, why?
I just want to do something when I tap everywhere of the list item.

It's ok when tap on the item's Text(), but when I tap blank space of the item, nothing happened, why?

```<code>struct ItemView: View {
    var body: some View {
        HStack {
            Text("Hello")
            Spacer()
            Text("world")
        }
    }
}

struct ListView: View {
    var body: some View {
        List() {
            ForEach((1...10).reversed(), id: \.self) { index in
                ItemView().onTapGesture {
                    print("item \(index) taped")
                }
            }
        }
    }
}
</code>```

-=-=-=

I do some experiments, they are so weird!!!

    print "hello" if tap the Text hello;

    print "world" if tap the blank space;

    print "item 0" tapped if tap the Text world;

```<code>struct ItemView: View {
    var body: some View {
        HStack {
            Text("Hello").onTapGesture {
                print("hello tapped")
            }
            Spacer()
            Button(action: {
                print("world tapped")
            }) {
                Text("world")
            }
        }
    }
}

struct ListView: View {
    var body: some View {
        List() {
            ForEach((1...10).reversed(), id: \.self) { index in
                ItemView().onTapGesture {
                    print("item \(index) taped")
                }
            }
        }
    }
}
</code>```

答:
Add background modifier to your ItemView with opacity

struct ContentView: View {
    var body: some View {
        List() {
            ForEach((1...10).reversed(), id: \.self) { index in
                ItemView()
                    .background(Color.gray.opacity(0.001))
                    .onTapGesture {
                    print("item \(index) taped")
                }
            }
        }
    }
}
```

Body:
I just want to do something when I tap everywhere of the list item.

It's ok when tap on the item's Text(), but when I tap blank space of the item, nothing happened, why?

struct ItemView: View {
    var body: some View {
        HStack {
            Text("Hello")
            Spacer()
            Text("world")
        }
    }
}

struct ListView: View {
    var body: some View {
        List() {
            ForEach((1...10).reversed(), id: \.self) { index in
                ItemView().onTapGesture {
                    print("item \(index) taped")
                }
            }
        }
    }
}

-=-=-=

I do some experiments, they are so weird!!!

    print "hello" if tap the Text hello;

    print "world" if tap the blank space;

    print "item 0" tapped if tap the Text world;

struct ItemView: View {
    var body: some View {
        HStack {
            Text("Hello").onTapGesture {
                print("hello tapped")
            }
            Spacer()
            Button(action: {
                print("world tapped")
            }) {
                Text("world")
            }
        }
    }
}

struct ListView: View {
    var body: some View {
        List() {
            ForEach((1...10).reversed(), id: \.self) { index in
                ItemView().onTapGesture {
                    print("item \(index) taped")
                }
            }
        }
    }
}


问:
Angular router warning - did you forget to call ngZone.run()
I am getting this error every time i am trying to redirect to a link in the same application from google map. I am using agmmap and angular 8. Here is the sample code

```<code><agm-map <some configuration there>>
  <agm-marker <some configuration there>>
    <agm-snazzy-info-window <some configuration there> #infoWindow>
      <ng-template>
        <a routerLink="/details">{{'view_details' | translate}}</a>
        </ng-template>
    </agm-snazzy-info-window>
  </agm-marker>
</agm-map>
</code>```

I am able to fix that issue using this Tutorial, but i wanted to know like what is the root cause of it and is there any change / refactoring required in the code to resolve it?

答:
This error asks you to call ngZone.run().

Since your error occurred every time you wanted to redirect to the same application google map you should call ngZone.run() after grantOfflineAccess().

grantOfflineAccess will be called when the user grants the requested scope (according to link)

I recommend you to read the error messages probably, this will lead you to fix  90% of the issues

Body:
I am getting this error every time i am trying to redirect to a link in the same application from google map. I am using agmmap and angular 8. Here is the sample code

<agm-map <some configuration there>>
  <agm-marker <some configuration there>>
    <agm-snazzy-info-window <some configuration there> #infoWindow>
      <ng-template>
        {{'view_details' | translate}}
        </ng-template>
    </agm-snazzy-info-window>
  </agm-marker>
</agm-map>

I am able to fix that issue using this Tutorial, but i wanted to know like what is the root cause of it and is there any change / refactoring required in the code to resolve it?


问:
Which line in the code
Is there any way to get which line of the code is running?

E.g. in some method I ran another programm and I'm waiting to ending. Now I want to know which line called this program without using breakpoints

答:
Just Ctrl-Break to pause the debugger; if you didn't even start in the debugger, you can 'Attach Process', and do the same.

Note that line number information will be present only if compiled with debug information (usually on only for Debug build configurations)

Title: Which line in the code


问:
Span hover not working and how to change properties of elements outside of div
Is there a way for me to hover on the span text ("engpar1call") and have the div called "engpar1" appear on the screen?

In my CSS file, I have my body set up such that the content appears in 2 columns; "transpar1" is always visible on the left, and "engpar1" is supposed to appear when the span "engpar1call" is hovered over. I can't seem to get the :hover to work, but I am able to style the span.

.content {
  color: white;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  display: none;
  transition-duration: 0.5s;
}

span.engpar1call {
  color: #D93636;
}
```

<pre class="lang-html prettyprint-override"><code>    <body>
      <div class="content">
        <div class="transpar1">
          <p>
            O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o
<span class="engpar1call">vaalele</span> i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
            o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
            mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
            ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.
          </p>
        </div>

        <div class="engpar1">
          <p>
            The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
            and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
            One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
            other, satisfy one's fecal necessities.
          </p>
        </div>
      </div>
</code>```

I've done a bit of searching, and I saw some Javascript that may be of help to me? But I'm not sure if I wrote it correctly because when I tried it, it wasn't working either.

```<code>    var engpar1call = document.getElementsByClassName(".engpar1call");

function showengpar1() {
    var engpar1 = document.getElementsByClassName(".engpar1");

    engpar1.style.display = "inline";
}
engpar1call.addEventListener("mouseover", showengpar1);
</code>```

答:
 $('.engpar1call').hover(
  function(){$('.engpar1').css('display', 'block')},
  function(){$('.engpar1').css('display', '')},
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .content {
  color: black;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  display: none;
  transition-duration: 0.5s;
}

span.engpar1call {
  color: #D93636;
}</code>```

            O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o
vaalele i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
            o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
            mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
            ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.

            The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
            and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
            One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
            other, satisfy one's fecal necessities.

```

Body:
Is there a way for me to hover on the span text ("engpar1call") and have the div called "engpar1" appear on the screen?

In my CSS file, I have my body set up such that the content appears in 2 columns; "transpar1" is always visible on the left, and "engpar1" is supposed to appear when the span "engpar1call" is hovered over. I can't seem to get the :hover to work, but I am able to style the span.

.content {
  color: white;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  display: none;
  transition-duration: 0.5s;
}

span.engpar1call {
  color: #D93636;
}

            O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o
vaalele i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
            o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
            mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
            ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.

            The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
            and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
            One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
            other, satisfy one's fecal necessities.

I've done a bit of searching, and I saw some Javascript that may be of help to me? But I'm not sure if I wrote it correctly because when I tried it, it wasn't working either.

    var engpar1call = document.getElementsByClassName(".engpar1call");

function showengpar1() {
    var engpar1 = document.getElementsByClassName(".engpar1");

    engpar1.style.display = "inline";
}
engpar1call.addEventListener("mouseover", showengpar1);

Body:
 $('.engpar1call').hover(
  function(){$('.engpar1').css('display', 'block')},
  function(){$('.engpar1').css('display', '')},
);

 .content {
  color: black;
  font-size: 10vh;
  font-weight: 700;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 2.5rem;
  grid-template-rows: 1;
  text-align: left;
}

.engpar1 {
  font-size: 10vh;
  font-weight: 700;
  grid-column: 2;
  grid-row: 1;
  display: none;
  transition-duration: 0.5s;
}

span.engpar1call {
  color: #D93636;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="content">
        <div class="transpar1">
          <p>
            O le atulaulau (lea e taua e le isi o le Potutusi) o se numera e le mafaitaulia ma atonu e le iʻu o fale o le hexagonal, faatasi ai ma le tele o
<span class="engpar1call">vaalele</span> i le va, e siʻosiʻomia e nofoaafi maualalo. Mai soʻo se tasi
            o le hexagons e mafai e se tasi ona vaʻavaʻai, vavalalata, pito i luga ma lalo. O le tufatufaina o faletusi e le mafai ona faʻaaogaina. Luasefulu fata, lima fata uumi i le tasi itu, ufiufi uma itu sei vagana ai lua; latou maualuga, o le mamao
            mai le fola i luga o le taualuga, e toetoe lava a sili atu nai lo se tusi tusi masani. O se tasi o itu saoloto e tau atu i se ala laupapa vaapiapi lea e tatalaina i luga o le isi avanoa, e tutusa lelei ma le muamua ma isi mea uma. I le tauagavale
            ma le taumatau o le alatele, e lua tamaʻi kapoti laiti. I le taimi muamua, e mafai ona moe se tasi; i le isi, faamalie mea e manaʻomia e le tagata.
          </p>
        </div>

        <div class="engpar1">
          <p>
            The universe (which others call the Library) is composed of an indefinite and perhaps infinite number of hexagonal galleries, with vast air shafts between, surrounded by very low railings. From any of the hexagons one can see, interminably, the upper
            and lower floors. The distribution of the galleries is invariable. Twenty shelves, five long shelves per side, cover all the sides except two; their height, which is the distance from floor to ceiling, scarcely exceeds that of a normal bookcase.
            One of the free sides leads to a narrow hallway which opens onto another gallery,identical to the first and to all the rest. To the left and right of the hallway there are two very small closets. In the first, one may sleep standing up; in the
            other, satisfy one's fecal necessities.
          </p>
        </div>
      </div>


问:
Azure VM Extension provisioning has taken too long to complete
When i am trying to deploy a template with extension i am getting timed out error as "Provisioning of VM extension InstallLamp has timed out. Extension provisioning has taken too long to complete. The extension did not report a message"

I am trying to install MySql through extension in a VM.

here is the extension code

```<code>{
"type": "Microsoft.Compute/virtualMachines/extensions",
"apiVersion": "2018-06-01",
"name": "[concat(variables('vmName'),'/', 'InstallMySQL')]",
"location": "[parameters('location')]",
"dependsOn": [
    "[concat('Microsoft.Compute/virtualMachines/',variables('vmName'))]"
],
"properties": {
    "publisher": "Microsoft.Compute",
    "type": "CustomScriptExtension",
    "typeHandlerVersion": "1.7",
    "autoUpgradeMinorVersion":true,
    "settings": {
        "fileUris": [
            "<url of custom script>"
        ],
        "commandToExecute": "sampleScript.sh"
    }
}
</code>```

Here is the sampleScript.sh code

```<code>sudo apt-get -y update
dbpass=12345678
export DEBIAN_FRONTEND=noninteractive
echo "mysql-server-5.7 mysql-server/root_password password" $dbpass | sudo debconf-set-selections >>
echo "mysql-server-5.7 mysql-server/root_password_again password" $dbpass | sudo debconf-set-selections
sudo apt-get -y install mysql-server-5.7
sudo apt-get -y install apache2 php7
sudo service apache2 restart
</code>```

答:
For this issue, the mistake you made is that the commands in the script are still interactive because of the command sudo. When you use the command sudo, it will need you to input the password of the root user.

And as I know, the VM extension already has the root permission to install the software. So you do not need to use the command sudo in your script. You just need to be sure the script is available and change it like this:

```<code>apt-get -y update
dbpass=12345678
export DEBIAN_FRONTEND=noninteractive
echo "mysql-server-5.7 mysql-server/root_password password" $dbpass | debconf-set-selections
echo "mysql-server-5.7 mysql-server/root_password_again password" $dbpass | debconf-set-selections
apt-get -y install mysql-server-5.7
apt-get -y install apache2 php7
service apache2 restart
</code>```

Body:
When i am trying to deploy a template with extension i am getting timed out error as "Provisioning of VM extension InstallLamp has timed out. Extension provisioning has taken too long to complete. The extension did not report a message"

I am trying to install MySql through extension in a VM.

here is the extension code

{
"type": "Microsoft.Compute/virtualMachines/extensions",
"apiVersion": "2018-06-01",
"name": "[concat(variables('vmName'),'/', 'InstallMySQL')]",
"location": "[parameters('location')]",
"dependsOn": [
    "[concat('Microsoft.Compute/virtualMachines/',variables('vmName'))]"
],
"properties": {
    "publisher": "Microsoft.Compute",
    "type": "CustomScriptExtension",
    "typeHandlerVersion": "1.7",
    "autoUpgradeMinorVersion":true,
    "settings": {
        "fileUris": [
            "<url of custom script>"
        ],
        "commandToExecute": "sampleScript.sh"
    }
}

Here is the sampleScript.sh code

sudo apt-get -y update
dbpass=12345678
export DEBIAN_FRONTEND=noninteractive
echo "mysql-server-5.7 mysql-server/root_password password" $dbpass | sudo debconf-set-selections >>
echo "mysql-server-5.7 mysql-server/root_password_again password" $dbpass | sudo debconf-set-selections
sudo apt-get -y install mysql-server-5.7
sudo apt-get -y install apache2 php7
sudo service apache2 restart

Body:
For this issue, the mistake you made is that the commands in the script are still interactive because of the command sudo. When you use the command sudo, it will need you to input the password of the root user.

And as I know, the VM extension already has the root permission to install the software. So you do not need to use the command sudo in your script. You just need to be sure the script is available and change it like this:

apt-get -y update
dbpass=12345678
export DEBIAN_FRONTEND=noninteractive
echo "mysql-server-5.7 mysql-server/root_password password" $dbpass | debconf-set-selections
echo "mysql-server-5.7 mysql-server/root_password_again password" $dbpass | debconf-set-selections
apt-get -y install mysql-server-5.7
apt-get -y install apache2 php7
service apache2 restart


问:
check if an array is a palindrome or not with just index as a parameter

import java.util.Scanner;

public class Palindrome1 {

    public static boolean palindrome(int[] num, int index) {
        //write the logic here

            int length = num.length;
            int end = --length;

            if (length == 0 || length == 1)
                return true;

            if (index >= end)
               return true;

            if(num[index]!=num[end])
                return false;

            return palindrome(num, index+1);
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num[] = new int[5];
        for(int i=0; i< 5;i++)
            num[i]=sc.nextInt();
        boolean answer =palindrome(num, 0);
        System.out.println(answer);
    }
}
```

It is easy if I had an end index value where I could have auto decremented. However with just index how can we solve it? Remember I should not be changing the number of params for the isPalindrome method.

Thanks in advance.

答:
From https://www.geeksforgeeks.org/program-to-check-if-an-array-is-palindrome-or-not/</p>

```<code>class GfG {

    static void palindrome(int arr[], int n)
    {
        // Initialise flag to zero.
        int flag = 0;

        // Loop till array size n/2.
        for (int i = 0; i <= n / 2 && n != 0; i++) {

            // Check if first and last element are different
            // Then set flag to 1.
            if (arr[i] != arr[n - i - 1]) {
                flag = 1;
                break;
            }
        }

        // If flag is set then print Not Palindrome
        // else print Palindrome.
        if (flag == 1)
            System.out.println("Not Palindrome");
        else
            System.out.println("Palindrome");
    }

    // Driver code.
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 2, 1 };
        int n = arr.length;

        palindrome(arr, n);
    }
}
</code>```

Body:
import java.util.Scanner;

public class Palindrome1 {

    public static boolean palindrome(int[] num, int index) {
        //write the logic here

            int length = num.length;
            int end = --length;

            if (length == 0 || length == 1)
                return true;

            if (index >= end)
               return true;

            if(num[index]!=num[end])
                return false;

            return palindrome(num, index+1);
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num[] = new int[5];
        for(int i=0; i< 5;i++)
            num[i]=sc.nextInt();
        boolean answer =palindrome(num, 0);
        System.out.println(answer);
    }
}

It is easy if I had an end index value where I could have auto decremented. However with just index how can we solve it? Remember I should not be changing the number of params for the isPalindrome method.

Thanks in advance.

Body:
From https://www.geeksforgeeks.org/program-to-check-if-an-array-is-palindrome-or-not/

class GfG {

    static void palindrome(int arr[], int n)
    {
        // Initialise flag to zero.
        int flag = 0;

        // Loop till array size n/2.
        for (int i = 0; i <= n / 2 && n != 0; i++) {

            // Check if first and last element are different
            // Then set flag to 1.
            if (arr[i] != arr[n - i - 1]) {
                flag = 1;
                break;
            }
        }

        // If flag is set then print Not Palindrome
        // else print Palindrome.
        if (flag == 1)
            System.out.println("Not Palindrome");
        else
            System.out.println("Palindrome");
    }

    // Driver code.
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 2, 1 };
        int n = arr.length;

        palindrome(arr, n);
    }
}


问:
Initializing Vuex parameter with a value from an array
I have this code for Vuex and I wanted to initialize a parameter's default value to a value from a Vuex array. How do I do this?

```<code>passcode: this.state.passcodes[0].value
</code>```

It results to an error stating

```<code>Cannot read property 'state' of undefined
</code>```

```<code>const store = new Vuex.Store({
  state: {
    passcodes: [
      {
        label: 'Pass1',
        value: '123456',
      },
      {
        label: 'Pass2',
        value: '654321',
      }
    ],
    data: [
      {
        name: '',
        passcode: this.state.passcode[0].value
      }
    ]
  }
})
</code>```

How do I do this??

答:
Use a Getter like this:

```<code>const store = new Vuex.Store({
  state: {
    passcodes: [
      { label: 'Pass1', value: 123456 },
      { label: 'Pass2', value: 654321 }
    ]
  },
  getters: {
    defaultPass: state => {
      return state.passcodes[0]
    }
  }
})
</code>```

You can then access your default setting via store.getters.defaultPass.

Or a mutation like this:

```<code>const store = new Vuex.Store({
  state: {
    passcodes: [
      { label: 'Pass1', value: 123456 },
      { label: 'Pass2', value: 654321 }
    ],
    defaultPass: '',
  },
  mutations: {
    default(state, n): {
      state.defaultPass = state.passcodes[n]
    }
  }
})
</code>```

You can then set your default value with store.commit('default', 0).

Body:
I have this code for Vuex and I wanted to initialize a parameter's default value to a value from a Vuex array. How do I do this?

passcode: this.state.passcodes[0].value

It results to an error stating

Cannot read property 'state' of undefined

const store = new Vuex.Store({
  state: {
    passcodes: [
      {
        label: 'Pass1',
        value: '123456',
      },
      {
        label: 'Pass2',
        value: '654321',
      }
    ],
    data: [
      {
        name: '',
        passcode: this.state.passcode[0].value
      }
    ]
  }
})

How do I do this??

Body:
Use a Getter like this:

const store = new Vuex.Store({
  state: {
    passcodes: [
      { label: 'Pass1', value: 123456 },
      { label: 'Pass2', value: 654321 }
    ]
  },
  getters: {
    defaultPass: state => {
      return state.passcodes[0]
    }
  }
})

You can then access your default setting via store.getters.defaultPass.

Or a mutation like this:

const store = new Vuex.Store({
  state: {
    passcodes: [
      { label: 'Pass1', value: 123456 },
      { label: 'Pass2', value: 654321 }
    ],
    defaultPass: '',
  },
  mutations: {
    default(state, n): {
      state.defaultPass = state.passcodes[n]
    }
  }
})

You can then set your default value with store.commit('default', 0).


问:
How to properly replace/remove azure private agents
I want to replace or possibly remove the private agents in our azure devops instance. I know that I can achieve this by using either the virtual machine scale sets or by containerize. The problem is I don't know which method is most efficient. Since I have never used any of the two</p>

答:
If you want to remove the private agents in your Azure DevOps instance in bulk, you can write a script to call the Pools - Get REST API to loop through your organization  and delete the agents by calling (Agents - Delete) REST API. Of course you must have delete permission to do that.

You can use below PowerShell script to achieve that, but please NOTE that you have set the filter correctly, otherwise the other agents may be deleted by mistake.

```<code>Param(
   [string]$orgurl = "https://dev.azure.com/{organization}",
   [string]$user = "username",
   [string]$token = "Password/PAT"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

#Get pools ID
$PoolsUrl = "$orgurl/_apis/distributedtask/pools?api-version=5.1"
$poolresponse = Invoke-RestMethod -Uri $PoolsUrl -Method Get -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
$poolids = $poolresponse.value.id

Cls

foreach ($poolid in $poolids)
{
 #Get agents in each pool
 $agentsurl = "$orgurl/_apis/distributedtask/pools/$poolid/agents?api-version=5.1"
 $agentresponse = Invoke-RestMethod -Uri $agentsurl -Method Get -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

 #Filter agents，please be sure you have set the filter correctly, avoid accidental deletion
 $privateagents = ($agentresponse.value | where {$_.name -like 'Private*'})

 $agenturls = $privateagents._links.self.href

 #Delete private agents:
   foreach ($agenturl in $agenturls)
   {
     $deleturl = $agenturl + "?api-version=5.1"
     $deleteresponse = Invoke-RestMethod -Uri $deleturl -Method DELETE -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
     Write-Host $deleteresponse
   }

}
</code>```

Body:
If you want to remove the private agents in your Azure DevOps instance in bulk, you can write a script to call the Pools - Get REST API to loop through your organization  and delete the agents by calling (Agents - Delete) REST API. Of course you must have delete permission to do that.

You can use below PowerShell script to achieve that, but please NOTE that you have set the filter correctly, otherwise the other agents may be deleted by mistake.

Param(
   [string]$orgurl = "https://dev.azure.com/{organization}",
   [string]$user = "username",
   [string]$token = "Password/PAT"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

#Get pools ID
$PoolsUrl = "$orgurl/_apis/distributedtask/pools?api-version=5.1"
$poolresponse = Invoke-RestMethod -Uri $PoolsUrl -Method Get -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
$poolids = $poolresponse.value.id

Cls

foreach ($poolid in $poolids)
{
 #Get agents in each pool
 $agentsurl = "$orgurl/_apis/distributedtask/pools/$poolid/agents?api-version=5.1"
 $agentresponse = Invoke-RestMethod -Uri $agentsurl -Method Get -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

 #Filter agents，please be sure you have set the filter correctly, avoid accidental deletion
 $privateagents = ($agentresponse.value | where {$_.name -like 'Private*'})

 $agenturls = $privateagents._links.self.href

 #Delete private agents:
   foreach ($agenturl in $agenturls)
   {
     $deleturl = $agenturl + "?api-version=5.1"
     $deleteresponse = Invoke-RestMethod -Uri $deleturl -Method DELETE -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
     Write-Host $deleteresponse
   }

}


问:
Page count of Pdf with Java
at the moment I am using itext to read the page count of a pdf. This takes quite long because the lib seems to scan the whole file.

Is the page information somewhere in the header of the pdf, or is a full filescan needed?

答: You just need to read the Page tree (Catalogue, Pages, Kids)  and count the Page entries.</p>

Title: Page count of Pdf with Java


问:
EXPLICIT_ACCESS array from ACL - WIN32 API
```<code>void main() {

    PSID UserSID = NULL;
    PSID GroupSID = NULL;
    PSECURITY_DESCRIPTOR SD = NULL;
    ACL *pDACL = new ACL ;

    string input, ext = "";
    wcout << "Enter the location : " << endl;
    std::getline(cin, input);
    LPCSTR file = input.c_str();

    HANDLE hFile = CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() == ERROR_ACCESS_DENIED)
        {
            cout << "Access Denied : System Files" << endl;
            return;
        }
        else if (GetLastError() == ERROR_PATH_NOT_FOUND)
        {
            cout << "Path Name Not Found" << endl;
            return;
        }
        else if (GetLastError() == ERROR_FILE_NOT_FOUND)
        {
            cout << "File Not Found" << endl;
            return;
        }
        else
        {
            cout << GetLastError() << endl;
            return;
        }
    }

    ULONG Count = NULL;
    PEXPLICIT_ACCESS_W *pExplicitEntries = new PEXPLICIT_ACCESS_W;

    if (GetSecurityInfo(hFile,SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &SD) == ERROR_SUCCESS)
    {
        cout << "GetSecInfo Success " << pDACL->AceCount << endl;
        cout << GetLastError() << endl;
    }

    if (GetExplicitEntriesFromAclW(pDACL, &Count, pExplicitEntries) == ERROR_SUCCESS)
    {
        cout << Count << endl;
        cout << GetLastError() << endl;
    }

    if (pExplicitEntries[0]->Trustee.TrusteeForm == TRUSTEE_IS_SID)
    {
        TCHAR AccountBuff[80];
        TCHAR DomainBuff[80];
        DWORD AccountBufflength = 40;
        DWORD DomainBufflength = 40;
        PSID_NAME_USE peUse = new SID_NAME_USE;
        PSID Sid = pExplicitEntries[0]->Trustee.ptstrName;

        LookupAccountSidW(NULL, Sid, AccountBuff, &AccountBufflength, DomainBuff, &DomainBufflength, peUse);

        wcout << AccountBuff << endl;

        DWORD pAccessRights;

        if (GetEffectiveRightsFromAclW(pDACL, &pExplicitEntries[0]->Trustee, &pAccessRights) == ERROR_SUCCESS)
        {
            DisplayAccessMask(pAccessRights);
        }
    }
}
</code>```

Currently, the array index is 0, if i switch to other index like 1 or 2, it causes exception : Accessing location. Please Help, please someone give me solution to access all the trustee in the ACL and get the access permission and username of each trustee of a file

答:
GetSecurityInfo gives me ACE count as 4 , but when it comes to the
  GetExplicitEntriesFromAclW the Count value remains 0.

I can reproduce this issue when my test target file is an new created, for example, TXT file. Yes, GetSecurityInfo gives me ACE count as 4 , but when it comes to the GetExplicitEntriesFromAclW the Count value remains 0.

Use function to check the ACE type and found that all types are 0: ACCESS_MIN_MS_ACE_TYPE \ ACCESS_ALLOWED_ACE_TYPE.

```<code>if (GetSecurityInfo(hFile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &SD) == ERROR_SUCCESS)
{
    cout << "GetSecInfo Success " << pDACL->AceCount << endl;
    cout << GetLastError() << endl;
}
PACL pAcl = pDACL;
int aceNum = pDACL->AceCount;
for (int i = 0; i < aceNum; i++)
{
    ACE_HEADER *aceAddr = NULL;
    if (GetAce(pAcl, i, (void**)(&aceAddr)))
    {
        printf("ACE type: %d \n",aceAddr->AceType); ACCESS_ALLOWED_ACE_TYPE;
        printf("ACE flags: %d \n", aceAddr->AceFlags);
        printf("ACE size: %d \n", aceAddr->AceSize);
    }
}
</code>```

If you set deny write operation for current user like this:

Then ACE type 1 (ACCESS_DENIED_ACE_TYPE) appears. And the Count value returned from the GetExplicitEntriesFromAclW equals the number of entries whose ACE type is 1. See the following snapshot:

Body:
void main() {

    PSID UserSID = NULL;
    PSID GroupSID = NULL;
    PSECURITY_DESCRIPTOR SD = NULL;
    ACL *pDACL = new ACL ;

    string input, ext = "";
    wcout << "Enter the location : " << endl;
    std::getline(cin, input);
    LPCSTR file = input.c_str();

    HANDLE hFile = CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() == ERROR_ACCESS_DENIED)
        {
            cout << "Access Denied : System Files" << endl;
            return;
        }
        else if (GetLastError() == ERROR_PATH_NOT_FOUND)
        {
            cout << "Path Name Not Found" << endl;
            return;
        }
        else if (GetLastError() == ERROR_FILE_NOT_FOUND)
        {
            cout << "File Not Found" << endl;
            return;
        }
        else
        {
            cout << GetLastError() << endl;
            return;
        }
    }

    ULONG Count = NULL;
    PEXPLICIT_ACCESS_W *pExplicitEntries = new PEXPLICIT_ACCESS_W;

    if (GetSecurityInfo(hFile,SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &SD) == ERROR_SUCCESS)
    {
        cout << "GetSecInfo Success " << pDACL->AceCount << endl;
        cout << GetLastError() << endl;
    }

    if (GetExplicitEntriesFromAclW(pDACL, &Count, pExplicitEntries) == ERROR_SUCCESS)
    {
        cout << Count << endl;
        cout << GetLastError() << endl;
    }

    if (pExplicitEntries[0]->Trustee.TrusteeForm == TRUSTEE_IS_SID)
    {
        TCHAR AccountBuff[80];
        TCHAR DomainBuff[80];
        DWORD AccountBufflength = 40;
        DWORD DomainBufflength = 40;
        PSID_NAME_USE peUse = new SID_NAME_USE;
        PSID Sid = pExplicitEntries[0]->Trustee.ptstrName;

        LookupAccountSidW(NULL, Sid, AccountBuff, &AccountBufflength, DomainBuff, &DomainBufflength, peUse);

        wcout << AccountBuff << endl;

        DWORD pAccessRights;

        if (GetEffectiveRightsFromAclW(pDACL, &pExplicitEntries[0]->Trustee, &pAccessRights) == ERROR_SUCCESS)
        {
            DisplayAccessMask(pAccessRights);
        }
    }
}

Currently, the array index is 0, if i switch to other index like 1 or 2, it causes exception : Accessing location. Please Help, please someone give me solution to access all the trustee in the ACL and get the access permission and username of each trustee of a file

Body:
GetSecurityInfo gives me ACE count as 4 , but when it comes to the
  GetExplicitEntriesFromAclW the Count value remains 0.

I can reproduce this issue when my test target file is an new created, for example, TXT file. Yes, GetSecurityInfo gives me ACE count as 4 , but when it comes to the GetExplicitEntriesFromAclW the Count value remains 0.

Use function to check the ACE type and found that all types are 0: ACCESS_MIN_MS_ACE_TYPE \ ACCESS_ALLOWED_ACE_TYPE.

if (GetSecurityInfo(hFile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &SD) == ERROR_SUCCESS)
{
    cout << "GetSecInfo Success " << pDACL->AceCount << endl;
    cout << GetLastError() << endl;
}
PACL pAcl = pDACL;
int aceNum = pDACL->AceCount;
for (int i = 0; i < aceNum; i++)
{
    ACE_HEADER *aceAddr = NULL;
    if (GetAce(pAcl, i, (void**)(&aceAddr)))
    {
        printf("ACE type: %d \n",aceAddr->AceType); ACCESS_ALLOWED_ACE_TYPE;
        printf("ACE flags: %d \n", aceAddr->AceFlags);
        printf("ACE size: %d \n", aceAddr->AceSize);
    }
}

If you set deny write operation for current user like this:

Then ACE type 1 (ACCESS_DENIED_ACE_TYPE) appears. And the Count value returned from the GetExplicitEntriesFromAclW equals the number of entries whose ACE type is 1. See the following snapshot:


问:
Finding Max and min of the input value
```<code>#include <iostream>
using namespace std;

int main(){
int i;
int size;
float Array[9];
float max;
float min;

cout << "Enter size of the array: ";
for(int i=0. i<5; i++){
cin << Array[i];
}

max = Array[1];
min = Array[1];

for(int i=0; i<size; i++){
if(Array[i] > max){
  max = Array[i];
}
if(Array[i] < min){
  min = Array[i]
}
}

cout << "Maximum value " << max << endl;
cout << "Minimum value " << min << endl;
return 0;

}
</code>```

Just started to learn C/C++ and I am stuck trying to finding the minimum and maximum value of the input. Also I have to set the range at 9 inputs if its more or its a letter, then I have to display a warning to the user input certain amount.

答:
Well, there are a bunch of wrong things done in that code.

So, here is the fixed version:

```<code>#include <iostream>
using namespace std;

int main(){
    //int i; // No Need of this. Inside the for loops we already declare int with (int i = 0)
    int size;
    // float Array[9];  // The array should be dynamically allocated based on the size
    float * Array;
    float max;
    float min;

    cout << "Enter size of the array: ";

    cin >> size; // This line was missing, added to get the size
    Array = new float[size]; // Initializing the array with the given sie

    // for(int i=0. i<5; i++){ // Instead of "." should be ";", also instead of 5 used "size"
    for(int i=0; i<size; i++){
        //cin << Array[i]; // With cin use ">>" instead of "<<"
        cin >> Array[i];
    }

    // max = Array[1]; // Arrays always start with index 0 instead of 1
    // min = Array[1]; // Arrays always start with index 0 instead of 1
    max = Array[0];
    min = Array[0];

    for(int i=0; i<size; i++){
        if(Array[i] > max){
          max = Array[i];
        }
        if(Array[i] < min){
          // min = Array[i] // Semicolon was missing there
          min = Array[i];
        }
    }

    cout << "Maximum value " << max << endl;
    cout << "Minimum value " << min << endl;

    delete Array; // Deleting the dynamic array

    return 0;

}
</code>```

P.S. I've commented the wrong parts in the original code, added some comments describing why they are wrong and added the correct ones right after those comments.

Title: Finding Max and min of the input value

Body:
#include <iostream>
using namespace std;

int main(){
int i;
int size;
float Array[9];
float max;
float min;

cout << "Enter size of the array: ";
for(int i=0. i<5; i++){
cin << Array[i];
}

max = Array[1];
min = Array[1];

for(int i=0; i<size; i++){
if(Array[i] > max){
  max = Array[i];
}
if(Array[i] < min){
  min = Array[i]
}
}

cout << "Maximum value " << max << endl;
cout << "Minimum value " << min << endl;
return 0;

}

Just started to learn C/C++ and I am stuck trying to finding the minimum and maximum value of the input. Also I have to set the range at 9 inputs if its more or its a letter, then I have to display a warning to the user input certain amount.

Body:
Well, there are a bunch of wrong things done in that code.

So, here is the fixed version:

#include <iostream>
using namespace std;

int main(){
    //int i; // No Need of this. Inside the for loops we already declare int with (int i = 0)
    int size;
    // float Array[9];  // The array should be dynamically allocated based on the size
    float * Array;
    float max;
    float min;

    cout << "Enter size of the array: ";

    cin >> size; // This line was missing, added to get the size
    Array = new float[size]; // Initializing the array with the given sie

    // for(int i=0. i<5; i++){ // Instead of "." should be ";", also instead of 5 used "size"
    for(int i=0; i<size; i++){
        //cin << Array[i]; // With cin use ">>" instead of "<<"
        cin >> Array[i];
    }

    // max = Array[1]; // Arrays always start with index 0 instead of 1
    // min = Array[1]; // Arrays always start with index 0 instead of 1
    max = Array[0];
    min = Array[0];

    for(int i=0; i<size; i++){
        if(Array[i] > max){
          max = Array[i];
        }
        if(Array[i] < min){
          // min = Array[i] // Semicolon was missing there
          min = Array[i];
        }
    }

    cout << "Maximum value " << max << endl;
    cout << "Minimum value " << min << endl;

    delete Array; // Deleting the dynamic array

    return 0;

}

P.S. I've commented the wrong parts in the original code, added some comments describing why they are wrong and added the correct ones right after those comments.


问:
Jmeter moodle testing for max concurrent usage
I have a VPS where a moodle site is working (4GB, 4CPU,Centos). In its domain a production site and another subdomain a test site is functional.
I would like to test how many concurrent users can take a quiz on my server. I was told about JMeter and related moodle scripts to do that.
The documentation says JMeter test should not be conducted on a production server but only on development system.
Can I call the second moodle site on same server as a development system?

Do I need completely different vps for testing?

答:
Essentially, the approach in load testing is to either apply a set known amount of load (or multiple sets in series), usually measured in number of simultaneous requests per second and see how your server copes with it, or apply increasing levels of load one after the other until your server no longer responds in order to find up to which amount of load the server can withstand.

The rationale behind the recommendation that load testing not be performed on production sites are twofold.

The first and most important is that the high intensity load applied to the server in addition to the normal load of users making use of the service or site will almost certainly impact the experience of users and under higher loads they may well find they are unable to use the site or service at all.

The second is that with the act of load testing is a measurement exercise, thus with existing load on a server in the form of the usual users going about their business, even though it may be possibly be comparatively low in contrast with what the load test is dishing out, that load over and above what the load test also is applying will throw out the measurement the load test is attempting to make and render the results less useful than they may have been (by a potentially unknown amount given user activity can be unpredictable and not easily able to be isolated).

Given both your Moodle instances are based on the same VPS, performing a load test on your development instance while your main production instance is experiencing its usual user load would throw of your measurement somewhat at the very least, but importantly would likely cause some inconvenience or loss of service to your users who are making use of your production instance at the time.

An alternative could be to temporarily (for the purpose of the test) set up an identical clone of the VPS with all the same resources and so forth and test against that, decommissioning the clone afterwards so you're not paying for two VPSs unnecessarily.

Another alternative could possibly be perhaps to determine if there are periods of time regularly that you have no users, or very few users, attempting to use your Moodles, and then perhaps either taking advantage of a period with no users and/or scheduling a period of maintenance ahead of time with your users, setting your production Moodle to maintenance mode so no one logs in, and perform the load test against your development moodle.

Hope that helps!