问:
How modify regex to exclude some text?
I have regex as '@(?:@msU'. I need modify this expression to exclude , ), exclude ()

How can I modify my regex?

答:
Here is a alternative using DOMDocument. It's easier to use and check for some tags and/or attributes to remove.</p>

```<code><?php

$html = '<html><body>foo</body><script type="text/javascript"></script><script></script><script no-defer type="text/javascript"></script><script src="" no-defer type="text/javascript"></script></html>';
$doc = new DOMDocument();
$doc->loadHTML($html);
$scripts = $doc->getElementsByTagName('script');
for ($i = $scripts->length; --$i >= 0; ) {
    $item = $scripts->item($i);
    foreach($item->attributes as $att) {
        if($att->name == 'no-defer') {
            $item->parentNode->removeChild($item);
        }
    }
}

$newHtml = $doc->saveHtml();

print_r($newHtml);
</code>```

Title: How modify regex to exclude some text?

Body:
Here is a alternative using DOMDocument. It's easier to use and check for some tags and/or attributes to remove.

<?php

$html = '<html><body>foo</body><script type="text/javascript"></script><script></script><script no-defer type="text/javascript"></script><script src="" no-defer type="text/javascript"></script></html>';
$doc = new DOMDocument();
$doc->loadHTML($html);
$scripts = $doc->getElementsByTagName('script');
for ($i = $scripts->length; --$i >= 0; ) {
    $item = $scripts->item($i);
    foreach($item->attributes as $att) {
        if($att->name == 'no-defer') {
            $item->parentNode->removeChild($item);
        }
    }
}

$newHtml = $doc->saveHtml();

print_r($newHtml);


来源: stackexchange

问:
Is it possible to wait for all actions in the ofType operator to be called before calling next?
I have an array of redux actions which when ALL have been called I want to call another action in my epic. The actions in the array are changeable, dynamic. What I'm hoping to find would be the equivalent of the ofType operator working like this:

ofType(FETCH_USER_PROFILE_SUCCESS && FETCH_USER_PREFERENCES_SUCCESS)

When both actions have been called, another is called further down the pipe. Of course the ofType operator doesn't work like this. It only needs one of the actions to be called to continue.

I have read that combineLatest might be the solution here but I've had no luck. Below is what I imagine the solution could look like but obviously this doesn't work for me. Any suggestions would be appreciated.

```<code>const actions = ['FETCH_USER_PROFILE_SUCCESS', 'FETCH_USER_PREFERENCES_SUCCESS'];

const asTypes = actions.map((action) => ofType(action);

const userEpic = (action$, state$) =>
  action$.pipe(
    combineLatest(asTypes);
    mergeMap(() =>
      of({
        type: 'SET_USER_READY'
      })
    )
  );
</code>```

Following on from replies below:

Just to clear what I meant by dynamic. The array of actions might include more actions depending on a user's profile (e.g. 'FETCH_USER_POSTS_SUCCESS'), essentially an unknown number of actions depending on the user.

So, is possible to generate this dynamically:

zip(
    action$.pipe(ofType('FETCH_USER_PROFILE_SUCCESS')),
    action$.pipe(ofType('FETCH_USER_PREFERENCES_SUCCESS')),
  )

```<code>const actions = ['FETCH_USER_PROFILE_SUCCESS', 'FETCH_USER_PREFERENCES_SUCCESS', unknown number of more actions];

const actions = dynamic.forEach((action) => action$.pipe(ofType(action))

zip(
    actions
  )
</code>```

答:
There's numerous ways of approaching this because there are some important missing details. But I'll make some guesses :)

The biggest is whether the order in which they arrive matters. If it does not, using zip() is probably what you want. It will pair emissions 1:1 (actually any number of observables, not just two, e.g. 1:1:1 for three, etc)

Even in that case, there's the question of what you want to do if the rate you receive the actions varies between them. What happens if you receive FETCH_USER_PROFILE_SUCCESS's twice as fast as often as you receive FETCH_USER_PREFERENCES_SUCCESS's? Should you continue to buffer them? Do you drop them? Do you error?

If buffering them is fine or you otherwise provide guarantees they will always happen at the same rate, zip() is works.

Now if you want to make sure they come in some sequence, things get more complicated still. You'd likely have a chain utilizing mergeMap, switchMap, exhaustMap, or concatMap. Deciding which depends again on what you want to do if the rate you get the actions isn't always the same.

```<code>import { zip } from 'rxjs';
import { map, take, switchMap } from 'rxjs/operators';
import { ofType } from 'redux-observable';

// Pair up the emissions 1:1 but without regard to the sequence
// in which they are received i.e. they can be in either order
const userEpic = (action$, state$) =>
  zip(
    action$.pipe(ofType('FETCH_USER_PROFILE_SUCCESS')),
    action$.pipe(ofType('FETCH_USER_PREFERENCES_SUCCESS')),
    // ...etc more observables
  ).pipe(
    map(() => ({
      type: 'SET_USER_READY'
    }))
  );

// FETCH_USER_PROFILE_SUCCESS must come before FETCH_USER_PREFERENCES_SUCCESS
// and if we receive another FETCH_USER_PROFILE_SUCCESS before we get
// the FETCH_USER_PREFERENCES_SUCCESS, start over again (switchMap)
const userEpic = (action$, state$) =>
  action$.pipe(
    ofType('FETCH_USER_PROFILE_SUCCESS'),
    switchMap(() =>
      action$.pipe(
        ofType('FETCH_USER_PREFERENCES_SUCCESS'),
        take(1) // important! we only want to wait for one
      )
    ),
    map(() => ({
      type: 'SET_USER_READY'
    }))
  )
</code>```

The actions in the array are changeable, dynamic

It's not clear how you want them to change, so I didn't include a mechanism for doing so.

--

There's also a similar question here: https://stackoverflow.com/a/45554647/1770633

ContentLicense: CC BY-SA 4.0

Body:
I have an array of redux actions which when ALL have been called I want to call another action in my epic. The actions in the array are changeable, dynamic. What I'm hoping to find would be the equivalent of the ofType operator working like this:

ofType(FETCH_USER_PROFILE_SUCCESS && FETCH_USER_PREFERENCES_SUCCESS)

When both actions have been called, another is called further down the pipe. Of course the ofType operator doesn't work like this. It only needs one of the actions to be called to continue.

I have read that combineLatest might be the solution here but I've had no luck. Below is what I imagine the solution could look like but obviously this doesn't work for me. Any suggestions would be appreciated.

const actions = ['FETCH_USER_PROFILE_SUCCESS', 'FETCH_USER_PREFERENCES_SUCCESS'];

const asTypes = actions.map((action) => ofType(action);

const userEpic = (action$, state$) =>
  action$.pipe(
    combineLatest(asTypes);
    mergeMap(() =>
      of({
        type: 'SET_USER_READY'
      })
    )
  );

Following on from replies below:

Just to clear what I meant by dynamic. The array of actions might include more actions depending on a user's profile (e.g. 'FETCH_USER_POSTS_SUCCESS'), essentially an unknown number of actions depending on the user.

So, is possible to generate this dynamically:

zip(
    action$.pipe(ofType('FETCH_USER_PROFILE_SUCCESS')),
    action$.pipe(ofType('FETCH_USER_PREFERENCES_SUCCESS')),
  )

const actions = ['FETCH_USER_PROFILE_SUCCESS', 'FETCH_USER_PREFERENCES_SUCCESS', unknown number of more actions];

const actions = dynamic.forEach((action) => action$.pipe(ofType(action))

zip(
    actions
  )

Body:
There's numerous ways of approaching this because there are some important missing details. But I'll make some guesses :)

The biggest is whether the order in which they arrive matters. If it does not, using zip() is probably what you want. It will pair emissions 1:1 (actually any number of observables, not just two, e.g. 1:1:1 for three, etc)

Even in that case, there's the question of what you want to do if the rate you receive the actions varies between them. What happens if you receive FETCH_USER_PROFILE_SUCCESS's twice as fast as often as you receive FETCH_USER_PREFERENCES_SUCCESS's? Should you continue to buffer them? Do you drop them? Do you error?

If buffering them is fine or you otherwise provide guarantees they will always happen at the same rate, zip() is works.

Now if you want to make sure they come in some sequence, things get more complicated still. You'd likely have a chain utilizing mergeMap, switchMap, exhaustMap, or concatMap. Deciding which depends again on what you want to do if the rate you get the actions isn't always the same.

import { zip } from 'rxjs';
import { map, take, switchMap } from 'rxjs/operators';
import { ofType } from 'redux-observable';

// Pair up the emissions 1:1 but without regard to the sequence
// in which they are received i.e. they can be in either order
const userEpic = (action$, state$) =>
  zip(
    action$.pipe(ofType('FETCH_USER_PROFILE_SUCCESS')),
    action$.pipe(ofType('FETCH_USER_PREFERENCES_SUCCESS')),
    // ...etc more observables
  ).pipe(
    map(() => ({
      type: 'SET_USER_READY'
    }))
  );

// FETCH_USER_PROFILE_SUCCESS must come before FETCH_USER_PREFERENCES_SUCCESS
// and if we receive another FETCH_USER_PROFILE_SUCCESS before we get
// the FETCH_USER_PREFERENCES_SUCCESS, start over again (switchMap)
const userEpic = (action$, state$) =>
  action$.pipe(
    ofType('FETCH_USER_PROFILE_SUCCESS'),
    switchMap(() =>
      action$.pipe(
        ofType('FETCH_USER_PREFERENCES_SUCCESS'),
        take(1) // important! we only want to wait for one
      )
    ),
    map(() => ({
      type: 'SET_USER_READY'
    }))
  )

The actions in the array are changeable, dynamic

It's not clear how you want them to change, so I didn't include a mechanism for doing so.

--

There's also a similar question here: https://stackoverflow.com/a/45554647/1770633


问:
Vertically align a text inside a inline-block spine with parent container height in percentage
I am struggling to vertically align text iside a display: inline-block span.

This span is inside a container which has a height set as percentage of its wrapping container:

```<code><div class="wrap">
    <div class ="header">
        <span>test</span>
    </div>
</div>
</code>```

and css:

```<code>html, body {
    height:100%;
    max-height: 1440px;
    max-width: 1920px;
}

.wrap {
    width: 100%;
    height: 100%;
    max-width: 1920px;
    min-width: 1024px;
    max-height: 1440px;
    min-height: 768px;
    background: green;
}

.header {
   background: yellow;
   height: 4.44%;
}

.header span {
  display: inline-block;
  line-height:100%;
  height: 100%;
  vertical-align: middle;
  background: orange;
}
</code>```

and here is the Fiddle

I also tried display:table; and display:table-cell; combo but that didn't work.

Edited:

I also got a question: why line-height:100% doesn't work?

Please help!

答:
>> I also got a question: why line-height:100% doesn't work?

line-height in percentage is relative to the font-size of the element. Refer this.

So, if you want the height and line-height of '.header span' to be the same, you can get the computed height in javascript and then set it for line-height:

```<code>let divElement = document.getElementById('divId');
let height = document.defaultView.getComputedStyle(divElement).height;
divElement.style.lineHeight = height;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am struggling to vertically align text iside a display: inline-block span.

This span is inside a container which has a height set as percentage of its wrapping container:

        test

and css:

html, body {
    height:100%;
    max-height: 1440px;
    max-width: 1920px;
}

.wrap {
    width: 100%;
    height: 100%;
    max-width: 1920px;
    min-width: 1024px;
    max-height: 1440px;
    min-height: 768px;
    background: green;
}

.header {
   background: yellow;
   height: 4.44%;
}

.header span {
  display: inline-block;
  line-height:100%;
  height: 100%;
  vertical-align: middle;
  background: orange;
}

and here is the Fiddle

I also tried display:table; and display:table-cell; combo but that didn't work.

Edited:

I also got a question: why line-height:100% doesn't work?

Please help!

Body:
>> I also got a question: why line-height:100% doesn't work?

line-height in percentage is relative to the font-size of the element. Refer this.

So, if you want the height and line-height of '.header span' to be the same, you can get the computed height in javascript and then set it for line-height:

let divElement = document.getElementById('divId');
let height = document.defaultView.getComputedStyle(divElement).height;
divElement.style.lineHeight = height;


问:
R Shiny and Integrated Google Charts
I am working to learn how to integrate Google Charts into a shiny app without using the additional overhead of the googlevis package and baking most things into the app myself. Below is a simple Hello World example that, for now, has the elements I want properly contained within the app.

What I am trying to learn how to do is use the r data created in the object tmp() to populate the data table I am creating. The app below works, but the charts are populated from the data hard coded in the data object for now.

Is there a way my r dataframe can be used to populate the data array?

Minimal reproducible ui file

```<code>ui <- fluidPage(
    titlePanel("Hello Google Charts"),
    sidebarLayout(
        sidebarPanel(
            h1('Hello World')
        ),
    mainPanel(
        htmlTemplate("test3.html"),
        verbatimTextOutput('x')
        )
    )
)
</code>```

Minimal reproducible server file

```<code>server <- function(input, output) {
    tmp <- data.frame(v1 = rnorm(4), v2 = rnorm(4))
    output$x <- renderPrint({tmp})
}
</code>```

HTML file test3.html

```<code><html>
  <head>
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script type="text/javascript">
      google.charts.load('current', {'packages':['gauge']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['v1', 'v2'],
          ['1', -1.9372140],
          ['2', -1.5234370],
          ['3', 0.2374601],
          ['4', 1.0550744]
        ]);

        var options = {
          width: 400, height: 120,
          redFrom: 75, redTo: 100,
          yellowFrom:50, yellowTo: 75,
          minorTicks: 10
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

        chart.draw(data, options);

        setInterval(function() {
          data.setValue(0, 1, 40 + Math.round(60 * Math.random()));
          chart.draw(data, options);
        }, 10000);
        setInterval(function() {
          data.setValue(1, 1, 40 + Math.round(60 * Math.random()));
          chart.draw(data, options);
        }, 100);
        setInterval(function() {
          data.setValue(2, 1, 10 );
          chart.draw(data, options);
        }, 100);
      }
    </script>
  </head>

  <body>
    <div id="chart_div" style="width: 400px; height: 120px;">
    </div>
  </body>
</html>
</code>```

答:
In order to send something from R to JavaScript, you have to use Shiny.addCustomMessageHandler in the JavaScript script and session$sendCustomMessage in the Shiny server (see ?shiny::session).

Here is a working app.

JavaScript file shinyHandler.js, to put in the www subfolder of the app:

$(document).ready(function(){
  google.charts.load('current', {'packages':['gauge']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart(data) {

    var options = {
      width: 400,
      height: 120,
      redFrom: 75,
      redTo: 100,
      yellowFrom:50,
      yellowTo: 75,
      minorTicks: 10
    };

    var chart =
      new google.visualization.Gauge(document.getElementById("chart_div"));

    var gdata = new google.visualization.DataTable(data);
    chart.draw(gdata, options);

/*    setInterval(function() {
      gdata.setValue(0, 1, 40 + Math.round(60 * Math.random()));
      chart.draw(gdata, options);
    }, 10000);
    setInterval(function() {
      gdata.setValue(1, 1, 40 + Math.round(60 * Math.random()));
      chart.draw(gdata, options);
    }, 100);
    setInterval(function() {
      gdata.setValue(2, 1, 10 );
      chart.draw(gdata, options);
    }, 100); */
  }

  Shiny.addCustomMessageHandler("chart", function(data){drawChart(data);});

});
```

<p>And the shiny app:</p>

<pre class="lang-r prettyprint-override"><code>library(shiny)

dataframe2datatable <- function(dat){
  list(
    rows = lapply(1:nrow(dat), function(i){
      list(c = lapply(unname(as.list(dat[i,])), function(x) list(v = x)))
    }),
    cols = lapply(names(dat), function(x){
      list(
        label = x,
        type = ifelse(mode(dat[[x]]) == "character", "string", "number")
      )
    })
  )
}

dat <- data.frame(
  v1 = as.character(1:4),
  v2 = rnorm(4),
  stringsAsFactors = FALSE
)

ui <- fluidPage(
  tags$head(
    tags$script(src = "https://www.gstatic.com/charts/loader.js"),
    tags$script(src = "shinyHandler.js")
  ),
  br(),
  actionButton("draw", "Draw chart"),
  br(),
  div(id = "chart_div")
)

server <- function(input, output, session){

  observeEvent(input[["draw"]], {
    session$sendCustomMessage("chart", dataframe2datatable(dat))
  })

}

shinyApp(ui, server)
</code>```

Title: R Shiny and Integrated Google Charts

Body:
I am working to learn how to integrate Google Charts into a shiny app without using the additional overhead of the googlevis package and baking most things into the app myself. Below is a simple Hello World example that, for now, has the elements I want properly contained within the app.

What I am trying to learn how to do is use the r data created in the object tmp() to populate the data table I am creating. The app below works, but the charts are populated from the data hard coded in the data object for now.

Is there a way my r dataframe can be used to populate the data array?

Minimal reproducible ui file

ui <- fluidPage(
    titlePanel("Hello Google Charts"),
    sidebarLayout(
        sidebarPanel(
            h1('Hello World')
        ),
    mainPanel(
        htmlTemplate("test3.html"),
        verbatimTextOutput('x')
        )
    )
)

Minimal reproducible server file

server <- function(input, output) {
    tmp <- data.frame(v1 = rnorm(4), v2 = rnorm(4))
    output$x <- renderPrint({tmp})
}

HTML file test3.html

Body:
In order to send something from R to JavaScript, you have to use Shiny.addCustomMessageHandler in the JavaScript script and session$sendCustomMessage in the Shiny server (see ?shiny::session).

Here is a working app.

JavaScript file shinyHandler.js, to put in the www subfolder of the app:

$(document).ready(function(){
  google.charts.load('current', {'packages':['gauge']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart(data) {

    var options = {
      width: 400,
      height: 120,
      redFrom: 75,
      redTo: 100,
      yellowFrom:50,
      yellowTo: 75,
      minorTicks: 10
    };

    var chart =
      new google.visualization.Gauge(document.getElementById("chart_div"));

    var gdata = new google.visualization.DataTable(data);
    chart.draw(gdata, options);

/*    setInterval(function() {
      gdata.setValue(0, 1, 40 + Math.round(60 * Math.random()));
      chart.draw(gdata, options);
    }, 10000);
    setInterval(function() {
      gdata.setValue(1, 1, 40 + Math.round(60 * Math.random()));
      chart.draw(gdata, options);
    }, 100);
    setInterval(function() {
      gdata.setValue(2, 1, 10 );
      chart.draw(gdata, options);
    }, 100); */
  }

  Shiny.addCustomMessageHandler("chart", function(data){drawChart(data);});

});

And the shiny app:

library(shiny)

dataframe2datatable <- function(dat){
  list(
    rows = lapply(1:nrow(dat), function(i){
      list(c = lapply(unname(as.list(dat[i,])), function(x) list(v = x)))
    }),
    cols = lapply(names(dat), function(x){
      list(
        label = x,
        type = ifelse(mode(dat[[x]]) == "character", "string", "number")
      )
    })
  )
}

dat <- data.frame(
  v1 = as.character(1:4),
  v2 = rnorm(4),
  stringsAsFactors = FALSE
)

ui <- fluidPage(
  tags$head(
    tags$script(src = "https://www.gstatic.com/charts/loader.js"),
    tags$script(src = "shinyHandler.js")
  ),
  br(),
  actionButton("draw", "Draw chart"),
  br(),
  div(id = "chart_div")
)

server <- function(input, output, session){

  observeEvent(input[["draw"]], {
    session$sendCustomMessage("chart", dataframe2datatable(dat))
  })

}

shinyApp(ui, server)


问:
Define a maximum number of line in a div
I create a  with a text inside but the text is too large for the div :

How can I stop the text when the div is stopping ?

答:
One option is line-clamp. It works on all browsers except IE11.

You can control how many lines want to show. Optionally, you can expand the content on hover / active / focus.

.content {
  margin: 0 1em;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.content:hover,
.content:active,
.content:focus {
  -webkit-line-clamp: unset;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></code>```

Body:
One option is line-clamp. It works on all browsers except IE11.

You can control how many lines want to show. Optionally, you can expand the content on hover / active / focus.

.content {
  margin: 0 1em;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.content:hover,
.content:active,
.content:focus {
  -webkit-line-clamp: unset;
}

<p class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>


问:
Python function that takes lists and elements and makes one list
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

```<code>def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]
</code>```

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!

答:
You can make a good use of *args in python.
Just traverse through the list of arguements and check whether the arguement is a list or not(by checking its type). If it is, just append that arguement to the one_big_list_of_all_elements.
Pretty simple!

Body:
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!


问:
JS split array to make sub-arrays and find a union set of all arrays
I've data in the following format:

Element 1: "Europe > Germany > Berlin > Main Office" (Object)

Element 2: "America > United States > Headquarters" (Object)

Element 3: "America > United States > NY > Main Office" (Object)

Element 4: "America > United States > NY > Sub Office" (Object)

Element 5: "United Kingdom > England > London > Main Office" (Object)

First I'm trying to split the array based on ">" character, and create a tree of all elements in the following format (vanilla js/es6):

"Europe": {
  "Germany": {
    "Berlin": {
      "Main Office": "Object"
    }
  }
},
```

<p>My attempt:</p>

```Array.prototype.slice.call(elements).forEach((el) => {

    let
    stringIHave = el.name, // "Europe > Germany > Berlin > Main Office"
    keywordsArr = stringIHave.split( " > " ),
    arrayTree =  new Array();

    Array.prototype.slice.call(keywordsArr).forEach((subEl) => {
        //arrayTree.push(el.toString()); // Result: {"Europe", "Germany", "Berlin", "Main Office" }

        // What I'm Seeking:
        // "Europe": { "Germany": { "Berlin": { "Main Office": "Object" } } },

    });

});
```

<p>Once we have the data formatted, we need to find the union (or one single array) of all arrays, like below:</p>

```[
"Europe": {
  "Germany": {
    "Berlin": {
      "Main Office": "Object"
    }
  }
},

"America": {
  "United States": {
    "Headquarters",
    "NY": {
      "Main Office": "Object",
      "Sub Office": "Object"
    }
  }
},

"United Kingdom": {
  "England": {
    "London": {
      "Main Office": "Object"
    }
  }
}
]
```

I've been trying to using Array.from(new Set(masterArray)) for finding the union of all arrays, but no dice!

答:
You can use a recursive function for each string in the array to construct the nested objects.

const data = [
  'Element 1: Europe > Germany > Berlin > Main Office',

  'Element 2: America > United States > Headquarters',

  'Element 3: America > United States > NY > Main Office',

  'Element 4: America > United States > NY > Sub Office',

  'Element 5: United Kingdom > England > London > Main Office'
]

 //remove the string before ':' on all array elements.
 let data1 = data.map(str => str.slice( str.indexOf(':') +1, -1 ));

 let arrayTree = data1.map(str => convertToTree(str)) ;

 console.log(arrayTree);

 function convertToTree(str) {
     let places = str.split('>');

     if(places.length === 1) {
         return ({"Main Office": "Object"});
     }

     //the first part of the splited string should be the property and the remaining part will be converted
     //back to string and sent to the recursive function until the result of the split becomes a single element

     return ({ [places[0]]:convertToTree(places.slice(1).join('>'))  });
 }```

Body:
I've data in the following format:

Element 1: "Europe > Germany > Berlin > Main Office" (Object)

Element 2: "America > United States > Headquarters" (Object)

Element 3: "America > United States > NY > Main Office" (Object)

Element 4: "America > United States > NY > Sub Office" (Object)

Element 5: "United Kingdom > England > London > Main Office" (Object)

First I'm trying to split the array based on ">" character, and create a tree of all elements in the following format (vanilla js/es6):

"Europe": {
  "Germany": {
    "Berlin": {
      "Main Office": "Object"
    }
  }
},

My attempt:

Array.prototype.slice.call(elements).forEach((el) => {

    let
    stringIHave = el.name, // "Europe > Germany > Berlin > Main Office"
    keywordsArr = stringIHave.split( " > " ),
    arrayTree =  new Array();

    Array.prototype.slice.call(keywordsArr).forEach((subEl) => {
        //arrayTree.push(el.toString()); // Result: {"Europe", "Germany", "Berlin", "Main Office" }

        // What I'm Seeking:
        // "Europe": { "Germany": { "Berlin": { "Main Office": "Object" } } },

    });

});

Once we have the data formatted, we need to find the union (or one single array) of all arrays, like below:

[
"Europe": {
  "Germany": {
    "Berlin": {
      "Main Office": "Object"
    }
  }
},

"America": {
  "United States": {
    "Headquarters",
    "NY": {
      "Main Office": "Object",
      "Sub Office": "Object"
    }
  }
},

"United Kingdom": {
  "England": {
    "London": {
      "Main Office": "Object"
    }
  }
}
]

I've been trying to using Array.from(new Set(masterArray)) for finding the union of all arrays, but no dice!


问:
how to install ELKI on windows?
I would like to install ELKI on windows and use clustering methods from python source code. The official documentation on the installation and use of their methods is not clear, which makes it difficult to handle their tool.</p>

答:
It is a Java program. It does not need to be "installed".

If you have Java, you can just launch the jar file.

But the target audience are scientists and developers, these know how to run a Java program, and will want to check out the source code from Git anyway.

Title: how to install ELKI on windows?


问:
Merge strings of an array list based on certain elements HOW
I'd like to perform a function on a a list of data in at text file but I'm not sure how to go about it. My understanding of how to manipulate arrays and strings is weak, that is why I'm doing this project.

My text file looks like:

```<code>0, 0. 50 0.5 66;
1, 0. 69 2. 70;
2, 0.5 48 0.5 71;
3, 1. 47 1. 75;
4, 2. 52 1. 74;
5, 2. 71 1. 80;
6, 3. 65 1. 61;
7, 4. 62 1. 68;
</code>```

I'm looking for a result like this:

0, 0. 50 0.5 66 0. 69 2. 70;

1, 0.5 48 0.5 71;

2, 1. 47 1. 75;

3, 2. 52 1. 74 2. 71 1. 80;

4, 3. 65 1. 61;

5, 4. 62 1. 68;

The second elements of the first two entries is the same (0.)and I'd like to combine these entries onto the same line. The same for lines 4 and 5.

As I understand I must read my file into an array list, but I don't know how to query the array list to find all entries that have the same value for the second element, and then merge the entire entry with another entry.

I have no code to show because I don't know where to begin.

I appreciate any input.

答:
I would parse the input into a list of lists (or array of arrays or whatever collection you prefer).  I would implement a Comparator that compares based on the second element in a list.  You can then sort your main list or array.  Finally, you can iterate through your list of lists, combining adjacent lists using whatever your combinatorial logic is, producing a new list as the result.

On the other hand, if your input is always going to be sorted as you are showing, then you can skip the comparator implementation and sorting altogether and just iterate through your collection performing the combinations

Body:
I'd like to perform a function on a a list of data in at text file but I'm not sure how to go about it. My understanding of how to manipulate arrays and strings is weak, that is why I'm doing this project.

My text file looks like:

0, 0. 50 0.5 66;
1, 0. 69 2. 70;
2, 0.5 48 0.5 71;
3, 1. 47 1. 75;
4, 2. 52 1. 74;
5, 2. 71 1. 80;
6, 3. 65 1. 61;
7, 4. 62 1. 68;

I'm looking for a result like this:

0, 0. 50 0.5 66 0. 69 2. 70;

1, 0.5 48 0.5 71;

2, 1. 47 1. 75;

3, 2. 52 1. 74 2. 71 1. 80;

4, 3. 65 1. 61;

5, 4. 62 1. 68;

The second elements of the first two entries is the same (0.)and I'd like to combine these entries onto the same line. The same for lines 4 and 5.

As I understand I must read my file into an array list, but I don't know how to query the array list to find all entries that have the same value for the second element, and then merge the entire entry with another entry.

I have no code to show because I don't know where to begin.

I appreciate any input.


问:
Adding pull to refresh on webview for refreshing
I will add pull to refresh on my webview so it refresh my webview. i have seen all questions on this page but i can't find the good way to add pull to refresh...

Mainactivity.java

```<code>package com.vvhvb.hesselfeenstra.vvheerenveenseboys;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url ="http://heerenveenseboys.nl/";
        WebView view=(WebView) this.findViewById(R.id.webView);
        view.getSettings().setJavaScriptEnabled(true);
        view.getSettings().setBuiltInZoomControls(true);
        view.getSettings().setDisplayZoomControls(false);
        view.setWebViewClient(new WebViewClient());
        view.loadUrl(url);

    }

}
</code>```

content_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.vvhvb.hesselfeenstra.vvheerenveenseboys.MainActivity"
    tools:showIn="@layout/activity_main">

    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/webView"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>
</code>```

I hope anyone can help me and solve this problem for me.

答:
activity_main.xml

```<code><android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
<WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
        app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

For Kotllin:

MainActivity.kt

```<code>var mySwipeRefreshLayout: SwipeRefreshLayout? = null
var myWebView: WebView? = null
mySwipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.swipeContainer)

    mySwipeRefreshLayout?.setOnRefreshListener {
        Log.i("on refresh", "onRefresh called from SwipeRefreshLayout")

        // This method performs the actual data-refresh operation.
        // The method calls setRefreshing(false) when it's finished.
        myWebView?.reload();
    }
myWebView!!.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl("http://www.google.com")
            return false;
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            mySwipeRefreshLayout?.isRefreshing = false
        }
    }
</code>```

Body:
I will add pull to refresh on my webview so it refresh my webview. i have seen all questions on this page but i can't find the good way to add pull to refresh...

Mainactivity.java

package com.vvhvb.hesselfeenstra.vvheerenveenseboys;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url ="http://heerenveenseboys.nl/";
        WebView view=(WebView) this.findViewById(R.id.webView);
        view.getSettings().setJavaScriptEnabled(true);
        view.getSettings().setBuiltInZoomControls(true);
        view.getSettings().setDisplayZoomControls(false);
        view.setWebViewClient(new WebViewClient());
        view.loadUrl(url);

    }

}

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.vvhvb.hesselfeenstra.vvheerenveenseboys.MainActivity"
    tools:showIn="@layout/activity_main">

    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/webView"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

I hope anyone can help me and solve this problem for me.

Body:
activity_main.xml

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
<WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp"
        app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.v4.widget.SwipeRefreshLayout>

For Kotllin:

MainActivity.kt

var mySwipeRefreshLayout: SwipeRefreshLayout? = null
var myWebView: WebView? = null
mySwipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.swipeContainer)

    mySwipeRefreshLayout?.setOnRefreshListener {
        Log.i("on refresh", "onRefresh called from SwipeRefreshLayout")

        // This method performs the actual data-refresh operation.
        // The method calls setRefreshing(false) when it's finished.
        myWebView?.reload();
    }
myWebView!!.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl("http://www.google.com")
            return false;
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            mySwipeRefreshLayout?.isRefreshing = false
        }
    }


问:
SwiftUI: List does not update automatically after deleting all Core Data Entity entries
I know SwiftUI uses state-driven rendering. So I was assuming, when I delete Core Data Entity entries, that my List with Core Data elements gets refreshed immediately.
I use this code, which gets my Entity cleaned succesfully:

```<code>func deleteAll()
{
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ToDoItem.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
}
</code>```

To get the List in my View visually empty I have to leave the View afterwards (for example with " self.presentationMode.wrappedValue.dismiss()") and open it again. As if the values are still stored somewhere in the memory or something.
This is of course not user-friendly and I am sure I just oversee something that refreshes the List immediately.
Maybe someone can help.

答:
The reason is that execute (as described in details below - pay attention on first sentence) does not affect managed objects context, so all fetched objects remains in context and UI represents what is really presented by context.

So in general, after this bulk operation you need to inform back to that code (not provided here) force sync and refetch everything.

API interface declaration

```<code>// Method to pass a request to the store without affecting the contents of the managed object context.
// Will return an NSPersistentStoreResult which may contain additional information about the result of the action
// (ie a batch update result may contain the object IDs of the objects that were modified during the update).
// A request may succeed in some stores and fail in others. In this case, the error will contain information
// about each individual store failure.
// Will always reject NSSaveChangesRequests.
@available(iOS 8.0, *)
open func execute(_ request: NSPersistentStoreRequest) throws -> NSPersistentStoreResult
</code>```

For example it might be the following approach (scratchy)

```<code>// somewhere in View declaration
@State private var refreshingID = UUID()

...
// somewhere in presenting fetch results
ForEach(fetchedResults) { item in
    ...
}.id(refreshingID) // < unique id of fetched results

...

// somewhere in bulk delete
try context.save() // < better to save everything pending
try context.execute(deleteRequest)
context.reset() // < reset context
self.refreshingID = UUID() // < force refresh
</code>```

Body:
I know SwiftUI uses state-driven rendering. So I was assuming, when I delete Core Data Entity entries, that my List with Core Data elements gets refreshed immediately.
I use this code, which gets my Entity cleaned succesfully:

func deleteAll()
{
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ToDoItem.fetchRequest()
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

    do {
        try persistentContainer.viewContext.execute(deleteRequest)
    } catch let error as NSError {
        print(error)
    }
}

To get the List in my View visually empty I have to leave the View afterwards (for example with " self.presentationMode.wrappedValue.dismiss()") and open it again. As if the values are still stored somewhere in the memory or something.
This is of course not user-friendly and I am sure I just oversee something that refreshes the List immediately.
Maybe someone can help.

Body:
The reason is that execute (as described in details below - pay attention on first sentence) does not affect managed objects context, so all fetched objects remains in context and UI represents what is really presented by context.

So in general, after this bulk operation you need to inform back to that code (not provided here) force sync and refetch everything.

API interface declaration

// Method to pass a request to the store without affecting the contents of the managed object context.
// Will return an NSPersistentStoreResult which may contain additional information about the result of the action
// (ie a batch update result may contain the object IDs of the objects that were modified during the update).
// A request may succeed in some stores and fail in others. In this case, the error will contain information
// about each individual store failure.
// Will always reject NSSaveChangesRequests.
@available(iOS 8.0, *)
open func execute(_ request: NSPersistentStoreRequest) throws -> NSPersistentStoreResult

For example it might be the following approach (scratchy)

// somewhere in View declaration
@State private var refreshingID = UUID()

...
// somewhere in presenting fetch results
ForEach(fetchedResults) { item in
    ...
}.id(refreshingID) // < unique id of fetched results

...

// somewhere in bulk delete
try context.save() // < better to save everything pending
try context.execute(deleteRequest)
context.reset() // < reset context
self.refreshingID = UUID() // < force refresh


问:
Passing list of variable names to custom function with mutate
I am trying to perform a function over each row and create a new column that considers multiple columns using tidyverse , I was initially using rowwise()  but that was very slow. I want the list of columns into my custom function be a variable, but I can't get it to work unless I explicitly list the variable names. For example, this works:

```<code>low_risk_codes <- c(0,1,10)
vars <- c("V1", "V2")
m <- matrix(1:9, ncol=3)
classify_low_risk_drug <- function(...){
  t <- cbind(...)
  return(apply(t, 1, function(x) ifelse(any(x %in% low_risk_codes), 1, 0)))
}

as.data.frame(m) %>%
  mutate(val4 = classify_low_risk_drug(V1, V2))
</code>```

But if I want it to evaluate using the column input as vars :

```<code>as.data.frame(m) %>%
  mutate(val4 = classify_low_risk_drug(vars))
</code>```

But I can't get it to work even if I include !!, what am I missing?!

Also any suggestions for how to do this with map instead are also appreciated!

答:
This sounds like it will do what you want, but I need to qualify it (a lot). First, FYI, I am still wrapping my mind around NSE in R but I find this vignette very helpful.

Related to the solution, I tried to speed up the function by avoiding rowwise() or apply(). It should be quicker with rapply()/rowSums() but I did not benchmark it. It may run into issues with very large data because rowSums() will convert the dataframe into a matrix but that probably wont be a problem. In theory, you should also be able to use select helpers / unquoted variable names / columns positions (if you so dare).

Also, I find it a little quirky that you need to supply the dataframe as the first argument (i.e., as .), but there may be a way around that. I am certainly open to anyway that wants to edit this / use this as the base for their solution. Hope this helps / gets you going in the right direction!

```<code>classify_low_risk_drug <- function(.data, vars, codes, na.rm = FALSE){

  df <- rapply(.data, function(x) x %in% codes, how = "replace")
  as.integer(rowSums(select(df, !!enquo(vars)), na.rm = na.rm) > 0)

  }

as.data.frame(m) %>%
  mutate(val4 = classify_low_risk_drug(., vars = vars, codes = c(0, 1, 10)))
  V1 V2 V3 val4
1  1  4  7    1
2  2  5  8    0
3  3  6  9    0
</code>```

EDIT: you could improve the speed a little bit by avoiding the matrix conversion / using lapply() w/ pmax():

```<code>classify_low_risk_drug2 <- function(.data, vars, codes, na.rm = FALSE){

  as.integer(do.call(pmax, lapply(select(.data, !!enquo(vars)), `%in%`, codes)))

}
</code>```

Body:
I am trying to perform a function over each row and create a new column that considers multiple columns using tidyverse , I was initially using rowwise()  but that was very slow. I want the list of columns into my custom function be a variable, but I can't get it to work unless I explicitly list the variable names. For example, this works:

low_risk_codes <- c(0,1,10)
vars <- c("V1", "V2")
m <- matrix(1:9, ncol=3)
classify_low_risk_drug <- function(...){
  t <- cbind(...)
  return(apply(t, 1, function(x) ifelse(any(x %in% low_risk_codes), 1, 0)))
}

as.data.frame(m) %>%
  mutate(val4 = classify_low_risk_drug(V1, V2))

But if I want it to evaluate using the column input as vars :

as.data.frame(m) %>%
  mutate(val4 = classify_low_risk_drug(vars))

But I can't get it to work even if I include !!, what am I missing?!

Also any suggestions for how to do this with map instead are also appreciated!

Body:
This sounds like it will do what you want, but I need to qualify it (a lot). First, FYI, I am still wrapping my mind around NSE in R but I find this vignette very helpful.

Related to the solution, I tried to speed up the function by avoiding rowwise() or apply(). It should be quicker with rapply()/rowSums() but I did not benchmark it. It may run into issues with very large data because rowSums() will convert the dataframe into a matrix but that probably wont be a problem. In theory, you should also be able to use select helpers / unquoted variable names / columns positions (if you so dare).

Also, I find it a little quirky that you need to supply the dataframe as the first argument (i.e., as .), but there may be a way around that. I am certainly open to anyway that wants to edit this / use this as the base for their solution. Hope this helps / gets you going in the right direction!

classify_low_risk_drug <- function(.data, vars, codes, na.rm = FALSE){

  df <- rapply(.data, function(x) x %in% codes, how = "replace")
  as.integer(rowSums(select(df, !!enquo(vars)), na.rm = na.rm) > 0)

  }

as.data.frame(m) %>%
  mutate(val4 = classify_low_risk_drug(., vars = vars, codes = c(0, 1, 10)))
  V1 V2 V3 val4
1  1  4  7    1
2  2  5  8    0
3  3  6  9    0

EDIT: you could improve the speed a little bit by avoiding the matrix conversion / using lapply() w/ pmax():

classify_low_risk_drug2 <- function(.data, vars, codes, na.rm = FALSE){

  as.integer(do.call(pmax, lapply(select(.data, !!enquo(vars)), `%in%`, codes)))

}


问:
The conditional check item.mount is failed
My playbook does not understand my variable DIRLOG and MOUNTS, am I missing the hierarchy?

STRUCTURE

```<code>playbooks
|   └── start_linux.yml
|
|
roles
|  └── preRequirements
|      └── tasks
|          └── main.yml
group_vars
  └── main.yml
</code>```

TASKS

```<code>    # Check space directory /var/logs/
      - name: 'Ensure that free space on /var/logs/ is grater than 1.5Gb'
        assert:
          that: item.size_available >= 1500000000
        when: item.mount == DIRLOG
        with_items: MOUNTS
        ignore_errors: yes
        register: disk_free

      - block:
          - debug:
              msg: "Disk (/var/logs/) space has reached 1.5Gb threshold"
          - meta: end_play
        when: disk_free is failed

  - debug:
      msg: "Sufficient disk space (/var/logs/), continue play"
</code>```

VARS

```<code>#################################################################################
# Variables global
#################################################################################

DIRLOG        : '/var/logs/'
MOUNTS        : "{{ ansible_mounts }}"
</code>```

PLAYBOOK

```<code># playbook for linux
---
- hosts: all
  vars_files:
    - ../group_vars/all.yml
  gather_facts: false
  tasks:
    - name: Check Pre Requirements for install agent
      import_role:
        name: preRequirements
        tasks_from: main
</code>```

ERROR

```<code>TASK [preRequirements : Ensure that free space on /var/logs/ is grater than 1.5Gb] ************************************************************************
fatal: [client_test]: FAILED! => {"msg": "The conditional check 'item.mount == DIRLOG' failed. The error was: error while evaluating conditional (item.mount == DIRLOG): 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'mount'\n\nThe error appears to be in '/etc/ansible/roles/preRequirements/tasks/main.yml': line 17, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n# Check space directory /var/logs/\n  - name: 'Ensure that free space on /var/logs/ is grater than 1.5Gb'\n    ^ here\n"}
...ignoring
</code>```

答:
The mistake was simple, a few hours of research follows a solution:

```<code>gather_facts: yes
</code>```

I will leave POST to help people with the same problem in the future

https://docs.ansible.com/ansible/latest/modules/gather_facts_module.html

Body:
My playbook does not understand my variable DIRLOG and MOUNTS, am I missing the hierarchy?

STRUCTURE

playbooks
|   └── start_linux.yml
|
|
roles
|  └── preRequirements
|      └── tasks
|          └── main.yml
group_vars
  └── main.yml

TASKS

    # Check space directory /var/logs/
      - name: 'Ensure that free space on /var/logs/ is grater than 1.5Gb'
        assert:
          that: item.size_available >= 1500000000
        when: item.mount == DIRLOG
        with_items: MOUNTS
        ignore_errors: yes
        register: disk_free

      - block:
          - debug:
              msg: "Disk (/var/logs/) space has reached 1.5Gb threshold"
          - meta: end_play
        when: disk_free is failed

  - debug:
      msg: "Sufficient disk space (/var/logs/), continue play"

VARS

#################################################################################
# Variables global
#################################################################################

DIRLOG        : '/var/logs/'
MOUNTS        : "{{ ansible_mounts }}"

PLAYBOOK

# playbook for linux
---
- hosts: all
  vars_files:
    - ../group_vars/all.yml
  gather_facts: false
  tasks:
    - name: Check Pre Requirements for install agent
      import_role:
        name: preRequirements
        tasks_from: main

ERROR

TASK [preRequirements : Ensure that free space on /var/logs/ is grater than 1.5Gb] ************************************************************************
fatal: [client_test]: FAILED! => {"msg": "The conditional check 'item.mount == DIRLOG' failed. The error was: error while evaluating conditional (item.mount == DIRLOG): 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'mount'\n\nThe error appears to be in '/etc/ansible/roles/preRequirements/tasks/main.yml': line 17, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n# Check space directory /var/logs/\n  - name: 'Ensure that free space on /var/logs/ is grater than 1.5Gb'\n    ^ here\n"}
...ignoring

Body:
The mistake was simple, a few hours of research follows a solution:

gather_facts: yes

I will leave POST to help people with the same problem in the future

https://docs.ansible.com/ansible/latest/modules/gather_facts_module.html


问:
LibGDX coordinates of intersection points between a Line Segment and a Circle
I'm working with LibGDX and I have a Line Segment (x1, y1, x2, y2) intersecting a circle with the center (cx, cy) and a radius R.

How can I determine the coordinates of the intersection points using LibGDX (or pure Java)?

I'm checked the Intersector.intersectSegmentCircle method, but this return only true or false without return the intersection points coordinates.

I thanks for any help.

答:
Not really an answer yet too long for a comment and using formatting that is only available for answers.

To find the intersecting points, mathematically, you need to solve two simultaneous equations. One for the circle and one for the straight line.

You can easily find the forms of these equations by searching the Internet.

Circle: (x - h)2 + (y - k)2 = r2

Line: y = mx + c

You can find the equation of a straight line given two points on the line and you claim to have two such points.

You also claim to have all the data for the circle, i.e. the co-ordinates of the circle's center plus the length of its radius.

You then need to search the Internet for how to solve simultaneous equations in java. I found this SO question:

How to solve a 2 variable linear simultaneous equation? Java


问:
Await isn't waiting?
Hi I've got two functions. They're called inside another function. And I need the second function execute after the first is done.

I'm sorry this is probably a very simple question, but I'm still trying to wrap my head around promises and async/await in js. Can anyone help me figure out why this isn't working.

```<code>async function addDetails(){
    const sub = await getSession();
    // now wait for firstFunction to finish...
    addProfileDetails(sub);
  };
</code>```

I have debug/logging statements in both. So I know that addProfileDetails is being executed before the variable sub is defined.

I'm using react native and node.js

EDIT:

```<code>export function getSession() {
  console.log("checking user ...............................................")
  Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      return payload.sub
  })
};
</code>```

This is my getSession() function. It also needs to be async?

答:
You must return a promise from the function that you want to await</p>

```<code>export function getSession() {
  console.log("checking user ...............................................")
  return Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      return payload.sub
  })
};
</code>```

Title: Await isn't waiting?

Body:
Hi I've got two functions. They're called inside another function. And I need the second function execute after the first is done.

I'm sorry this is probably a very simple question, but I'm still trying to wrap my head around promises and async/await in js. Can anyone help me figure out why this isn't working.

async function addDetails(){
    const sub = await getSession();
    // now wait for firstFunction to finish...
    addProfileDetails(sub);
  };

I have debug/logging statements in both. So I know that addProfileDetails is being executed before the variable sub is defined.

I'm using react native and node.js

EDIT:

export function getSession() {
  console.log("checking user ...............................................")
  Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      return payload.sub
  })
};

This is my getSession() function. It also needs to be async?

Body:
You must return a promise from the function that you want to await

export function getSession() {
  console.log("checking user ...............................................")
  return Auth.currentSession().then(res=>{
      console.log("retrieving token");
      let accessToken = res.getAccessToken()
      let payload = accessToken.payload;
      console.log(`sub: ${payload.sub}`)
      return payload.sub
  })
};


问:
using triggers to update Values
I'm trying to enhance the performance of a SQL Server 2000 job. Here's the scenario:

Table A has max. of 300,000 rows. If I update/delete the 100th row (Based on the insertion time) all the rows which has been added after that row, should update their values. Row no. 101, should update its value based on row no. 100 and row no. 102 should update its value based on the row no.101's updated value.  e.g.

Old Table:

```<code>ID...........Value
100..........220
101..........(220/2) = 110
102..........(110/2)=55
......................
</code>```

Row No. 100 updated with new value: 300.

New Table

```<code>ID...........Value
100..........300
101..........(300/2) = 150
102..........(150/2)=75
......................
</code>```

The actual values calculation is more complex. the formula is for simplicity.

Right now, a trigger is defined for update/delete statements. When a row is updated or deleted, the trigger adds the row's data to a log table. Also, a SQL Job is created in code-behind after update/delete which fires a stored procedure that finally, iterates through all the next rows of table A and updates their values. The process takes ~10 days to be accomplished for 300,000 rows.

When the SP gets fired, it updates the next rows' values. I think this causes the trigger to run again for each SP update and add these rows to the log table too. Also, The task should be done in DB-side as requested by customer.

To solve the problem:

Modify the stored procedure and call it directly from the trigger. The stored procedure then drops the trigger and updates the next rows' values and then creates the trigger again.

There will be multiple instances of the program running simultaneously. if another user modifies a row while the SP is being executed, the system will not fire the trigger and I'll be in trouble! Is there any workaround for this?

What's your opinion about this solution? Is there any better way to achieve this?

Thank you.

答:
First, about the update process. I understand, your procedure is simply calling itself, when it comes to updating the next row. With 300K rows this is certainly not going to be very fast, even without logging (though it would most probably take much fewer days to accomplish). But what is absolutely beyond me is how it is possible to update more than 32 rows that way without reaching the maximum nesting level. Maybe I've got the sequence of actions wrong.

Anyway, I would probably do that differently, with just one instruction:

```<code>UPDATE yourtable
SET @value = Value = CASE ID
                       WHEN @id THEN @value
                       ELSE @value / 2 /* basically, your formula */
                     END
WHERE ID >= @id
OPTION (MAXDOP 1);
</code>```

The OPTION (MAXDOP 1) bit of the statement limits the degree of parallelism for the statement to 1, thus making sure the rows are updated sequentially and every value is based on the previous one, i.e. on the value from the row with the preceding ID value. Also, the ID column should be made a clustered index, which it typically is by default, when it's made the primary key.

The other functionality of the update procedure, i.e. dropping and recreating the trigger, should probably be replaced by disabling and re-enabling it:

```<code>ALTER TABLE yourtable DISABLE TRIGGER yourtabletrigger

/* the update part */

ALTER TABLE yourtable ENABLE TRIGGER yourtabletrigger
</code>```

But then, you are saying the trigger shouldn't actually be dropped/disabled, because several users might update the table at the same time.

All right then, we are not touching the trigger.

Instead I would suggest adding a special column to the table, the one the users shouldn't be aware of, or at least shouldn't care much of and should somehow be made sure never to touch. That column should only be updated by your 'cascading update' process. By checking whether that column was being updated or not you would know whether you should call the update procedure and the logging.

So, in your trigger there could be something like this:

```<code>IF NOT UPDATE(SpecialColumn) BEGIN
  /* assuming that without SpecialColumn only one row can be updated */
  SELECT TOP 1 @id = ID, @value = Value FROM inserted;
  EXEC UpdateProc @id, @value;
  EXEC LogProc ...;
END
</code>```

In UpdateProc:

```<code>UPDATE yourtable
SET @value = Value = @value / 2,
    SpecialColumn = SpecialColumn /* basically, just anything, since it can
                                     only be updated by this procedure */
WHERE ID > @id
OPTION (MAXDOP 1);
</code>```

You may have noticed that the UPDATE statement is slightly different this time. I understand, your trigger is FOR UPDATE (= AFTER UPDATE), which means that the @id row is already going to be updated by the user. So the procedure should skip it and start from the very next row, and the update expression can now be just the formula.

In conclusion I'd like to say that my test update involved 299,995 of my table's 300,000 rows and took approximately 3 seconds on my not so very fast system. No logging, of course, but I think that should give your the basic picture of how fast it can be.

Title: using triggers to update Values

Body:
I'm trying to enhance the performance of a SQL Server 2000 job. Here's the scenario:

Table A has max. of 300,000 rows. If I update/delete the 100th row (Based on the insertion time) all the rows which has been added after that row, should update their values. Row no. 101, should update its value based on row no. 100 and row no. 102 should update its value based on the row no.101's updated value.  e.g.

Old Table:

ID...........Value
100..........220
101..........(220/2) = 110
102..........(110/2)=55
......................

Row No. 100 updated with new value: 300.

New Table

ID...........Value
100..........300
101..........(300/2) = 150
102..........(150/2)=75
......................

The actual values calculation is more complex. the formula is for simplicity.

Right now, a trigger is defined for update/delete statements. When a row is updated or deleted, the trigger adds the row's data to a log table. Also, a SQL Job is created in code-behind after update/delete which fires a stored procedure that finally, iterates through all the next rows of table A and updates their values. The process takes ~10 days to be accomplished for 300,000 rows.

When the SP gets fired, it updates the next rows' values. I think this causes the trigger to run again for each SP update and add these rows to the log table too. Also, The task should be done in DB-side as requested by customer.

To solve the problem:

Modify the stored procedure and call it directly from the trigger. The stored procedure then drops the trigger and updates the next rows' values and then creates the trigger again.

There will be multiple instances of the program running simultaneously. if another user modifies a row while the SP is being executed, the system will not fire the trigger and I'll be in trouble! Is there any workaround for this?

What's your opinion about this solution? Is there any better way to achieve this?

Thank you.

Body:
First, about the update process. I understand, your procedure is simply calling itself, when it comes to updating the next row. With 300K rows this is certainly not going to be very fast, even without logging (though it would most probably take much fewer days to accomplish). But what is absolutely beyond me is how it is possible to update more than 32 rows that way without reaching the maximum nesting level. Maybe I've got the sequence of actions wrong.

Anyway, I would probably do that differently, with just one instruction:

UPDATE yourtable
SET @value = Value = CASE ID
                       WHEN @id THEN @value
                       ELSE @value / 2 /* basically, your formula */
                     END
WHERE ID >= @id
OPTION (MAXDOP 1);

The OPTION (MAXDOP 1) bit of the statement limits the degree of parallelism for the statement to 1, thus making sure the rows are updated sequentially and every value is based on the previous one, i.e. on the value from the row with the preceding ID value. Also, the ID column should be made a clustered index, which it typically is by default, when it's made the primary key.

The other functionality of the update procedure, i.e. dropping and recreating the trigger, should probably be replaced by disabling and re-enabling it:

ALTER TABLE yourtable DISABLE TRIGGER yourtabletrigger

/* the update part */

ALTER TABLE yourtable ENABLE TRIGGER yourtabletrigger

But then, you are saying the trigger shouldn't actually be dropped/disabled, because several users might update the table at the same time.

All right then, we are not touching the trigger.

Instead I would suggest adding a special column to the table, the one the users shouldn't be aware of, or at least shouldn't care much of and should somehow be made sure never to touch. That column should only be updated by your 'cascading update' process. By checking whether that column was being updated or not you would know whether you should call the update procedure and the logging.

So, in your trigger there could be something like this:

IF NOT UPDATE(SpecialColumn) BEGIN
  /* assuming that without SpecialColumn only one row can be updated */
  SELECT TOP 1 @id = ID, @value = Value FROM inserted;
  EXEC UpdateProc @id, @value;
  EXEC LogProc ...;
END

In UpdateProc:

UPDATE yourtable
SET @value = Value = @value / 2,
    SpecialColumn = SpecialColumn /* basically, just anything, since it can
                                     only be updated by this procedure */
WHERE ID > @id
OPTION (MAXDOP 1);

You may have noticed that the UPDATE statement is slightly different this time. I understand, your trigger is FOR UPDATE (= AFTER UPDATE), which means that the @id row is already going to be updated by the user. So the procedure should skip it and start from the very next row, and the update expression can now be just the formula.

In conclusion I'd like to say that my test update involved 299,995 of my table's 300,000 rows and took approximately 3 seconds on my not so very fast system. No logging, of course, but I think that should give your the basic picture of how fast it can be.


问:
How can I override a method returning a List containing instances of subclass to the class the original methods List contained?
I realize the title is kind of messy, but that's the best I could come up with.

Below is a minimal example of what I wish, but am currently failing to do.

```<code>public class ObjectA {}

public class ObjectB extends ObjectA {}

public interface HandlerInterface<T extends ObjectA> {

        public T easyToOverride();

        public List<T> hardToOverride();

}

public class HandlerA implements HandlerInterface<ObjectA> {

        public ObjectA easyToOverride() {
                return new ObjectA();
        }

        public List<ObjectA> hardToOverride() {
                return new ArrayList<ObjectA>();
        }
}

public class HandlerB extends HandlerA implements HandlerInterface<ObjectB> {

        /*
          This method ovverides its super method with ease since its return
          type directly inherits from the super class's return type
        */
        public ObjectB easyToOverride() {
                return new ObjectB();
        }

        /*
          This method is NOT accepted by the Java syntax since List<ObjectB>
          does NOT directly inherit from List<ObjectA>

          The method signature for hardToOverride() clashes with the signature
          in the super class and is not overridden because the return types
          don't obviously inherit each other
        */
         public List<ObjectB> hardToOverride() {
                return new ArrayList<ObjectB>();
        }
}
</code>```

Ignore that these classes should be in their own files and that I have not included their imports. I just put it like this to make it easier to read.

As you may have understood by the comments in the class HandlerB, the method hardToOverride() is not accepted (throw this code into your IDE and watch it scream).

I realise I could just return a List<Object> and type cast the contents of the returned List object to the type that I personally know the specific handler instance returns (ObjectA or ObjectB), but that would mean that anyone using these methods has to understand the inner workings of them, and I do not like that.

What I want is to be able to override the List<ObjectA> hardToOverride() method with a method List<ObjectB> hardToOverride() without losing the hard typing that these methods provide.

So my final question is:

Is there any way to keep all of these interfaces, inheritances and overrides without loosing the strong typing they provide in my example code?

If not, what is a better way to achieve a similar set of classes and interfaces that actually works?

答:
Your code is accepted if you declare HandlerA with a new generic even if this is never used really:

```<code>public class HandlerA<T> implements HandlerInterface<ObjectA> {
//....
}
</code>```

NOTE: This is to be considered just a workaround but as result your example code will work as you asked. Moreover, even if HandlerA declares a generic, you can anycase instantiate it also without brackets:

```<code>ObjectA objectA = new HandlerA();
</code>```

Body:
I realize the title is kind of messy, but that's the best I could come up with.

Below is a minimal example of what I wish, but am currently failing to do.

public class ObjectA {}

public class ObjectB extends ObjectA {}

public interface HandlerInterface<T extends ObjectA> {

        public T easyToOverride();

        public List<T> hardToOverride();

}

public class HandlerA implements HandlerInterface<ObjectA> {

        public ObjectA easyToOverride() {
                return new ObjectA();
        }

        public List<ObjectA> hardToOverride() {
                return new ArrayList<ObjectA>();
        }
}

public class HandlerB extends HandlerA implements HandlerInterface<ObjectB> {

        /*
          This method ovverides its super method with ease since its return
          type directly inherits from the super class's return type
        */
        public ObjectB easyToOverride() {
                return new ObjectB();
        }

        /*
          This method is NOT accepted by the Java syntax since List<ObjectB>
          does NOT directly inherit from List<ObjectA>

          The method signature for hardToOverride() clashes with the signature
          in the super class and is not overridden because the return types
          don't obviously inherit each other
        */
         public List<ObjectB> hardToOverride() {
                return new ArrayList<ObjectB>();
        }
}

Ignore that these classes should be in their own files and that I have not included their imports. I just put it like this to make it easier to read.

As you may have understood by the comments in the class HandlerB, the method hardToOverride() is not accepted (throw this code into your IDE and watch it scream).

I realise I could just return a List<Object> and type cast the contents of the returned List object to the type that I personally know the specific handler instance returns (ObjectA or ObjectB), but that would mean that anyone using these methods has to understand the inner workings of them, and I do not like that.

What I want is to be able to override the List<ObjectA> hardToOverride() method with a method List<ObjectB> hardToOverride() without losing the hard typing that these methods provide.

So my final question is:

Is there any way to keep all of these interfaces, inheritances and overrides without loosing the strong typing they provide in my example code?

If not, what is a better way to achieve a similar set of classes and interfaces that actually works?

Body:
Your code is accepted if you declare HandlerA with a new generic even if this is never used really:

public class HandlerA<T> implements HandlerInterface<ObjectA> {
//....
}

NOTE: This is to be considered just a workaround but as result your example code will work as you asked. Moreover, even if HandlerA declares a generic, you can anycase instantiate it also without brackets:

ObjectA objectA = new HandlerA();


问:
How to make xmlroot a specific attribute in C#
I recently have change my program to deserialize XML files. I created a class but it needs to be under certain attribute. I thought using XmlRootAttribute would work but I keep getting the error

```<code>InvalidOperationException: <DataFileSetup xmlns=''> was not expected.
</code>```

Here is my code

```<code>[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftDevices
{
   [XmlElement(ElementName = "Devices")]
   public List<DewesoftSetup> dewesoftSiriusSetups { get; set; }

};

public class DewesoftSetup
{
   public double StartStoreTime;
   public int SampleRate;
   public int BlockSize;
   public int IBRate;
   public int AAFsr;
   public int MaxSampling;
   [XmlElement(ElementName = "Device")]
   public List<DeviceType> deviceType { get; set; }
};

public class DeviceType
{
   [XmlAttribute(AttributeName = "Type")]
   public string deviceType;

   [XmlElement(ElementName = "Slot")]
   public List<Slot> slot { get; set; }
};

public class Slot
{
   public string MeasuredValue { get; set; }
   public string Range { get; set; }
   public string LPFilter_Type { get; set; }
   public string LPFilter_Hz { get; set; }
   public string LPFilter_Order { get; set; }
   public string HPFilter_Hz { get; set; }
   public double AmplScale { get; set; }
   public double AmplOffset { get; set; }
   public string AmplShortInfo { get; set; }
   public string NamePrefix { get; set; }
   [XmlElement(ElementName = "OutputChannel")]
   public OutputChannel outputChannel;
   [XmlElement(ElementName = "AmplifierChainInfo/AmplifierInfo")]
   public AmplifierInfo ampInfo;
}

public class DewesoftCard
{
   public static string xmlFileName = @"C:\Dewesoft\SetupFile.xml";
   public double startStoreTime;
   public int sampleRate;
   public int blockSize;
   public int ibRate;
   public int aafSR;
   public int maxSampling;
   public int startZoomTime;
   public int endZoomTime;
};

public class OutputChannel
{
   public string Name { get; set; }
   public string Description { get; set; }
   public string Unit { get; set; }
   public int userScaleMin { get; set; }
   public int userScaleMax { get; set; }
   public int defaultComplexPresent { get; set; }
   public string Used { get; set; }
   public string Index { get; set; }
   public int DataType { get; set; }
   public double Scale { get; set; }
   public double Offset { get; set; }
   public double RangeMax { get; set; }
   public double RangeMin { get; set; }
   public int BitsLog { get; set; }
   public int SigBitCount { get; set; }
   public int BitsForMinMax { get; set; }
   public int BitCount { get; set; }
   public int ExportOrder { get; set; }
   public string MeasuredQuantity { get; set; }
   public int AmplifierScaleMin { get; set; }
   public int AmplifierScaleMax { get; set; }
};

public class AmplifierInfo
{
   public string Name { get; set; }
   public string Type { get; set; }
   public string SerialNr { get; set; }
   public string Revision { get; set; }
   public string Firmware { get; set; }
   public string CalDate { get; set; }
   public string Range { get; set; }
   public string LP_filter { get; set; }
   public string LP_filter_type { get; set; }
   public string LP_filter_order { get; set; }
   public string HP_filter { get; set; }
};

</code>```

```<code>public static void readXML()
{
   XmlReader reader = XmlReader.Create(DewesoftCard.xmlFileName);

   reader.ReadToFollowing("DewesoftSetup");

   XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
   DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
}

</code>```

```<code><?xml version="1.0" encoding="UTF-8"?>
<DataFileSetup>
    <System Name="Local">
        <SysInfo>
            <Software>
                <VersionCreated>X3 SP5 (RELEASE-181228) (64-bit)</VersionCreated>
                <VersionModifed>X3 SP5 (RELEASE-181228) (64-bit)</VersionModifed>
                <License_Type>Professional</License_Type>
            </Software>
         </SysInfo>
         <DewesoftSetup>
            <Devices>
                <StartStoreTime>43874.6969328704</StartStoreTime>
                <SampleRate>50000</SampleRate>
                <BlockSize>1000</BlockSize>
                <IBRate>10</IBRate>
                <AAFsr>21000</AAFsr>
                <MaxSampling>200000</MaxSampling>
                <Device Type="AI">
                    <Slot Index="0">
                        <MeasuredValue>VOLTAGE</MeasuredValue>
                        <Range>10 V</Range>
                        <LPFilter_Type>BU</LPFilter_Type>
                        <LPFilter_Hz>10000</LPFilter_Hz>
                        <LPFilter_Order>2</LPFilter_Order>
                        <HPFilter_Hz>1</HPFilter_Hz>
                        <OutMathChEnabled>8;1;0;0;0;0;0;0;0</OutMathChEnabled>
                        <OutputChannel>
                            <DisplayColor>#FFFF00</DisplayColor>
                            <Name>ACC-1X</Name>
                            <Description>Dome</Description>
                            <DefaultUnit>False</DefaultUnit>
                            <Unit>g</Unit>
                            <DefaultComplexPresent>1</DefaultComplexPresent>
                            <Used>True</Used>
                            <Index>AI;0</Index>
                            <DataType>4</DataType>
                            <Scale>200</Scale>
                            <RangeMax>2000</RangeMax>
                            <RangeMin>-2000</RangeMin>
                            <BitsLog>24</BitsLog>
                            <SigBitCount>19</SigBitCount>
                            <BitsForMinMax>24</BitsForMinMax>
                            <BitCount>24</BitCount>
                            <SIUnit>
                                <Label>g</Label>
                                <PhysicalQuantity>ACCELERATION</PhysicalQuantity>
                                <MetricPos>1</MetricPos>
                                <ImperialPos>1</ImperialPos>
                                <CustomPos>1</CustomPos>
                                <EditEnable>False</EditEnable>
                                <Scale>0.101972</Scale>
                            </SIUnit>
                            <MeasuredQuantity>ACCELERATION</MeasuredQuantity>
                            <OnlineInfo>
                                <IBStream Level="0"></IBStream>
                                <IBStream Level="1"></IBStream>
                                <IBStream Level="2"></IBStream>
                                <IBStream Level="3"></IBStream>
                                <IBStream Level="4"></IBStream>
                                <IBStream Level="5"></IBStream>
                            </OnlineInfo>
                            <AmplifierScaleMin>-10</AmplifierScaleMin>
                            <AmplifierScaleMax>10</AmplifierScaleMax>
                        </OutputChannel>
                        <AmplifierChainInfo>
                            <AmplifierInfo Index="0" Type="DEWEUSB_AMPLIFIER">
                                <Name>SIRIUS-HD-ACC</Name>
                                <SerialNr>D013C47522</SerialNr>
                                <Revision>1.3.0.0</Revision>
                                <Firmware>1.10</Firmware>
                                <CalDate>09.01.2020</CalDate>
                                <Measurement>Voltage</Measurement>
                                <Range>10 V</Range>
                                <LP_filter>10 kHz*  (HW: 100 kHz)</LP_filter>
                                <LP_filter_type>Butterworth*</LP_filter_type>
                                <LP_filter_order>2nd*</LP_filter_order>
                                <HP_filter>AC  1 Hz  (SW: 0.1 Hz)</HP_filter>
                            </AmplifierInfo>
                        </AmplifierChainInfo>
                   </Slot>
                </Device>
            </Devices>
        </DewesoftSetup>
  </System>
</DataFileSetup>
</code>```

There are multiple "Device" attributes but I need the one under DewesoftSetup.

EDIT i have added more of the xml document. I am trying to add the device type to a list and the slot to list since there will be multiples of them.

答:
Try following :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            readXML();
        }
        public static void readXML()
        {
            XmlReader reader = XmlReader.Create(FILENAME);

            reader.ReadToFollowing("DewesoftSetup");

            XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
            DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
        }
    }
    [XmlRoot(ElementName = "DewesoftSetup")]
    public class DewesoftDevices
    {
        [XmlElement(ElementName = "Devices")]
        public List<Devices> devices { get; set; }

    }

    public class Devices
    {
        public string StartStoreTime;
        public int SampleRate;
        public int IBRate;
        public int AAFsr;
        public int MaxSampling;

        [XmlElement(ElementName = "Device")]
        public List<DeviceType> deviceType { get; set; }
    }

    public class DeviceType
    {
        [XmlAttribute(AttributeName = "Type")]
        public string deviceType;

        [XmlElement(ElementName = "Slot")]
        public List<Slot> slot { get; set; }
    }
    public class Slot
    {
        public string Range { get; set; }
        public OutputChannel OutputChannel { get; set; }

        [XmlArray("AmplifierChainInfo")]
        [XmlArrayItem("AmplifierInfo")]
        public List<AmplifierInfo> AmplifierInfo { get; set; }
    }
    public class OutputChannel
    {
        public string Name { get; set; }
    }
    public class AmplifierInfo
    {
        public string Name { get; set; }
    }
}
</code>```

Body:
I recently have change my program to deserialize XML files. I created a class but it needs to be under certain attribute. I thought using XmlRootAttribute would work but I keep getting the error

InvalidOperationException: <DataFileSetup xmlns=''> was not expected.

Here is my code

[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftDevices
{
   [XmlElement(ElementName = "Devices")]
   public List<DewesoftSetup> dewesoftSiriusSetups { get; set; }

};

public class DewesoftSetup
{
   public double StartStoreTime;
   public int SampleRate;
   public int BlockSize;
   public int IBRate;
   public int AAFsr;
   public int MaxSampling;
   [XmlElement(ElementName = "Device")]
   public List<DeviceType> deviceType { get; set; }
};

public class DeviceType
{
   [XmlAttribute(AttributeName = "Type")]
   public string deviceType;

   [XmlElement(ElementName = "Slot")]
   public List<Slot> slot { get; set; }
};

public class Slot
{
   public string MeasuredValue { get; set; }
   public string Range { get; set; }
   public string LPFilter_Type { get; set; }
   public string LPFilter_Hz { get; set; }
   public string LPFilter_Order { get; set; }
   public string HPFilter_Hz { get; set; }
   public double AmplScale { get; set; }
   public double AmplOffset { get; set; }
   public string AmplShortInfo { get; set; }
   public string NamePrefix { get; set; }
   [XmlElement(ElementName = "OutputChannel")]
   public OutputChannel outputChannel;
   [XmlElement(ElementName = "AmplifierChainInfo/AmplifierInfo")]
   public AmplifierInfo ampInfo;
}

public class DewesoftCard
{
   public static string xmlFileName = @"C:\Dewesoft\SetupFile.xml";
   public double startStoreTime;
   public int sampleRate;
   public int blockSize;
   public int ibRate;
   public int aafSR;
   public int maxSampling;
   public int startZoomTime;
   public int endZoomTime;
};

public class OutputChannel
{
   public string Name { get; set; }
   public string Description { get; set; }
   public string Unit { get; set; }
   public int userScaleMin { get; set; }
   public int userScaleMax { get; set; }
   public int defaultComplexPresent { get; set; }
   public string Used { get; set; }
   public string Index { get; set; }
   public int DataType { get; set; }
   public double Scale { get; set; }
   public double Offset { get; set; }
   public double RangeMax { get; set; }
   public double RangeMin { get; set; }
   public int BitsLog { get; set; }
   public int SigBitCount { get; set; }
   public int BitsForMinMax { get; set; }
   public int BitCount { get; set; }
   public int ExportOrder { get; set; }
   public string MeasuredQuantity { get; set; }
   public int AmplifierScaleMin { get; set; }
   public int AmplifierScaleMax { get; set; }
};

public class AmplifierInfo
{
   public string Name { get; set; }
   public string Type { get; set; }
   public string SerialNr { get; set; }
   public string Revision { get; set; }
   public string Firmware { get; set; }
   public string CalDate { get; set; }
   public string Range { get; set; }
   public string LP_filter { get; set; }
   public string LP_filter_type { get; set; }
   public string LP_filter_order { get; set; }
   public string HP_filter { get; set; }
};

public static void readXML()
{
   XmlReader reader = XmlReader.Create(DewesoftCard.xmlFileName);

   reader.ReadToFollowing("DewesoftSetup");

   XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
   DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
}

<?xml version="1.0" encoding="UTF-8"?>
<DataFileSetup>
    <System Name="Local">
        <SysInfo>
            <Software>
                <VersionCreated>X3 SP5 (RELEASE-181228) (64-bit)</VersionCreated>
                <VersionModifed>X3 SP5 (RELEASE-181228) (64-bit)</VersionModifed>
                <License_Type>Professional</License_Type>
            </Software>
         </SysInfo>
         <DewesoftSetup>
            <Devices>
                <StartStoreTime>43874.6969328704</StartStoreTime>
                <SampleRate>50000</SampleRate>
                <BlockSize>1000</BlockSize>
                <IBRate>10</IBRate>
                <AAFsr>21000</AAFsr>
                <MaxSampling>200000</MaxSampling>
                <Device Type="AI">
                    <Slot Index="0">
                        <MeasuredValue>VOLTAGE</MeasuredValue>
                        <Range>10 V</Range>
                        <LPFilter_Type>BU</LPFilter_Type>
                        <LPFilter_Hz>10000</LPFilter_Hz>
                        <LPFilter_Order>2</LPFilter_Order>
                        <HPFilter_Hz>1</HPFilter_Hz>
                        <OutMathChEnabled>8;1;0;0;0;0;0;0;0</OutMathChEnabled>
                        <OutputChannel>
                            <DisplayColor>#FFFF00</DisplayColor>
                            <Name>ACC-1X</Name>
                            <Description>Dome</Description>
                            <DefaultUnit>False</DefaultUnit>
                            <Unit>g</Unit>
                            <DefaultComplexPresent>1</DefaultComplexPresent>
                            <Used>True</Used>
                            <Index>AI;0</Index>
                            <DataType>4</DataType>
                            <Scale>200</Scale>
                            <RangeMax>2000</RangeMax>
                            <RangeMin>-2000</RangeMin>
                            <BitsLog>24</BitsLog>
                            <SigBitCount>19</SigBitCount>
                            <BitsForMinMax>24</BitsForMinMax>
                            <BitCount>24</BitCount>
                            <SIUnit>
                                g
                                <PhysicalQuantity>ACCELERATION</PhysicalQuantity>
                                <MetricPos>1</MetricPos>
                                <ImperialPos>1</ImperialPos>
                                <CustomPos>1</CustomPos>
                                <EditEnable>False</EditEnable>
                                <Scale>0.101972</Scale>
                            </SIUnit>
                            <MeasuredQuantity>ACCELERATION</MeasuredQuantity>
                            <OnlineInfo>
                                <IBStream Level="0"></IBStream>
                                <IBStream Level="1"></IBStream>
                                <IBStream Level="2"></IBStream>
                                <IBStream Level="3"></IBStream>
                                <IBStream Level="4"></IBStream>
                                <IBStream Level="5"></IBStream>
                            </OnlineInfo>
                            <AmplifierScaleMin>-10</AmplifierScaleMin>
                            <AmplifierScaleMax>10</AmplifierScaleMax>
                        </OutputChannel>
                        <AmplifierChainInfo>
                            <AmplifierInfo Index="0" Type="DEWEUSB_AMPLIFIER">
                                <Name>SIRIUS-HD-ACC</Name>
                                <SerialNr>D013C47522</SerialNr>
                                <Revision>1.3.0.0</Revision>
                                <Firmware>1.10</Firmware>
                                <CalDate>09.01.2020</CalDate>
                                <Measurement>Voltage</Measurement>
                                <Range>10 V</Range>
                                <LP_filter>10 kHz*  (HW: 100 kHz)</LP_filter>
                                <LP_filter_type>Butterworth*</LP_filter_type>
                                <LP_filter_order>2nd*</LP_filter_order>
                                <HP_filter>AC  1 Hz  (SW: 0.1 Hz)</HP_filter>
                            </AmplifierInfo>
                        </AmplifierChainInfo>
                   </Slot>
                </Device>
            </Devices>
        </DewesoftSetup>
  </System>
</DataFileSetup>

There are multiple "Device" attributes but I need the one under DewesoftSetup.

EDIT i have added more of the xml document. I am trying to add the device type to a list and the slot to list since there will be multiples of them.

Body:
Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            readXML();
        }
        public static void readXML()
        {
            XmlReader reader = XmlReader.Create(FILENAME);

            reader.ReadToFollowing("DewesoftSetup");

            XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
            DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
        }
    }
    [XmlRoot(ElementName = "DewesoftSetup")]
    public class DewesoftDevices
    {
        [XmlElement(ElementName = "Devices")]
        public List<Devices> devices { get; set; }

    }

    public class Devices
    {
        public string StartStoreTime;
        public int SampleRate;
        public int IBRate;
        public int AAFsr;
        public int MaxSampling;

        [XmlElement(ElementName = "Device")]
        public List<DeviceType> deviceType { get; set; }
    }

    public class DeviceType
    {
        [XmlAttribute(AttributeName = "Type")]
        public string deviceType;

        [XmlElement(ElementName = "Slot")]
        public List<Slot> slot { get; set; }
    }
    public class Slot
    {
        public string Range { get; set; }
        public OutputChannel OutputChannel { get; set; }

        [XmlArray("AmplifierChainInfo")]
        [XmlArrayItem("AmplifierInfo")]
        public List<AmplifierInfo> AmplifierInfo { get; set; }
    }
    public class OutputChannel
    {
        public string Name { get; set; }
    }
    public class AmplifierInfo
    {
        public string Name { get; set; }
    }
}


问:
How can I set single child element in center align using css?
I have multiple child element in parent that divided with 3 columns and from 4 element goes to second row with left align:

ul {
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-flow: wrap;
}

li {
  width: 33.33%;
  flex: 0 0 33.33%;
  padding: 15px 0;
  background: #000;
  color: #fff;
  font-size: 1rem;
  text-align: center;
  margin-bottom: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Four</li>
</ul></code>```

But, when I have only a single child in my
 list, I want single child column into center.

答:
You can use CSS 3 Flexbox to achieve your specific requirement.

ul {
      display: flex;
      width: 150px;
      flex-flow: row wrap;
      justify-content: space-around;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

</head>
<body>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
  </ul>

  <ul>
    <li>One</li>
  </ul>

  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>

  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
</body>
</html></code>```

Ref: https://www.w3schools.com/css/css3_flexbox.asp

Body:
I have multiple child element in parent that divided with 3 columns and from 4 element goes to second row with left align:

ul {
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-flow: wrap;
}

li {
  width: 33.33%;
  flex: 0 0 33.33%;
  padding: 15px 0;
  background: #000;
  color: #fff;
  font-size: 1rem;
  text-align: center;
  margin-bottom: 15px;
}

One

Two

Three

Four

Four

But, when I have only a single child in my
 list, I want single child column into center.

Body:
You can use CSS 3 Flexbox to achieve your specific requirement.

ul {
      display: flex;
      width: 150px;
      flex-flow: row wrap;
      justify-content: space-around;
    }

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

</head>
<body>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
  </ul>

  <ul>
    <li>One</li>
  </ul>

  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>

  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
</body>
</html>

Ref: https://www.w3schools.com/css/css3_flexbox.asp