问:
How to dynamically control the visibility of controls in Liquid Template
In Liquid template is it possible to set visibility of the control dynamically based on the condition. For example i want the following output but input text boxes should only get visible when user clicks on corresponding radio button</p>

```<code><input type="radio" name="questions" value="q1" />Question 1<br />
<input type="text" name="ans1" /><br />
<input type="radio" name="questions" value="q2" />Question 2<br />
<input type="text" name="ans2" /><br />
<input type="radio" name="questions" value="q3" />Question 2<br />
<input type="text" name="ans3" /><br />
</code>```

答:
Liquid is executed server-side so this is not possible. You could create logic to hide them on load, but it would never change if you wrote it in liquid.

I think this would be best accomplished with JavaScript. All Shopify themes include jQuery as well which would be your golden ticket.

Here's an example:

```<code>const inputs = {
  'input_1': {
    hides: ['.some_option_1']
  },
  'input_2': {
    hides: ['.some_option_2', '.some_option_3']
  },
  'input_3': {
    hides: []
  }
};

for (let input_key in inputs) {
  const input = $(`[name="${input_key}"]`);

  input.on('click', () => {
    const hides = inputs[input_key].hides.join(',');

    $('.option').show();
    $(hides).hide();
  });
}
</code>```

With your HTML like so:

```<code><button name="input_1" placeholder="1">Input 1</button>
<button name="input_2" placeholder="2">Input 2</button>
<button name="input_3" placeholder="3">Input 3</button>

<p class="option some_option_1">
  Option 1
</p>
<p class="option some_option_2">
  Option 2
</p>
<p class="option some_option_3">
  Option 3
</p>
</code>```

Here's a JS fiddle: https://jsfiddle.net/brydom/16f894Lt/

Body:
In Liquid template is it possible to set visibility of the control dynamically based on the condition. For example i want the following output but input text boxes should only get visible when user clicks on corresponding radio button

<input type="radio" name="questions" value="q1" />Question 1

<input type="text" name="ans1" />

<input type="radio" name="questions" value="q2" />Question 2

<input type="text" name="ans2" />

<input type="radio" name="questions" value="q3" />Question 2

<input type="text" name="ans3" />

Body:
Liquid is executed server-side so this is not possible. You could create logic to hide them on load, but it would never change if you wrote it in liquid.

I think this would be best accomplished with JavaScript. All Shopify themes include jQuery as well which would be your golden ticket.

Here's an example:

const inputs = {
  'input_1': {
    hides: ['.some_option_1']
  },
  'input_2': {
    hides: ['.some_option_2', '.some_option_3']
  },
  'input_3': {
    hides: []
  }
};

for (let input_key in inputs) {
  const input = $(`[name="${input_key}"]`);

  input.on('click', () => {
    const hides = inputs[input_key].hides.join(',');

    $('.option').show();
    $(hides).hide();
  });
}

With your HTML like so:

<button name="input_1" placeholder="1">Input 1</button>
<button name="input_2" placeholder="2">Input 2</button>
<button name="input_3" placeholder="3">Input 3</button>

<p class="option some_option_1">
  Option 1
</p>
<p class="option some_option_2">
  Option 2
</p>
<p class="option some_option_3">
  Option 3
</p>

Here's a JS fiddle: https://jsfiddle.net/brydom/16f894Lt/


来源: stackexchange

问:
Is there an R function for identifying 'n' matches in each row?
I am attempting to aggregate my data to find correlations/patterns, and want to discover how and where data may correlate. Specifically, I want to identify how many times an id (here called 'item') appear together. Is there a way to find how many times each (id) appear together in a row?

This is for a larger data.frame that has already been cleaned and aggregated based on this particular inquiry. In the past, I have tried to apply multiple aggregation, summation and filter functions from packages like 'data.table','dplyr', and 'tidyverse' but cannot quite get what I am looking for.

In section 3(Show some code) I have provided a minimal reproducible example:

```<code>set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:12350,2000,replace = T)
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(cbind(number,item), stringsAsFactors = FALSE)
</code>```

Using the examples here,I expected the output to ID all the combinations where names were aggregated to a number and show the n (value) - expecting results to resemble something like:

```<code>Pair       value
Bob, Tim     2
Bob, Jackie  4
Bob, Angie   0
</code>```

This output (what I am hoping to get) would tell me that in the entire df, there are 2 times that Bob and Tim and 4 times that Bob and Jackie both have the same number.

but the actual output is:

```<code>Error: Each row of output must be identified by a unique combination of keys.

Keys are shared for 2000 rows:
* 9, 23, 37, 164, 170, 180, 211...
</code>```

Update: I thought of a..creative(?) solution - but hope someone can help with expedting it. I can locate all the numbers (column1) that are shared between two names using the following:

```<code>x1<-sample_data %>% dplyr::filter(item=="Bob")
x2<-sample_data %>% dplyr::filter(item=="Tim")
Bob<-x1[,1]
Tim<-x2[,1]
Reduce(intersect, list(Bob,Tim))
</code>```

output:

```<code>[1] "12345" "12348" "12350" "12346" "12349" "12347"
</code>```

Like I said, this is very time consuming and would require creating a plethora of vectors and intersecting each(e.g. 1 vector for each name) and multiple combinations.

答:
```<code>set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:22350,2000,replace = T) # I edited ur number here.
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(cbind(number,item), stringsAsFactors = FALSE)

library(tidyverse)
sample_data %>%
  # find out unique rows
  distinct() %>%
  # nest the data frame into nested tibble, so now you have
  # a "data" column, which is a list of small data frames.
  group_nest(number) %>%
  # Here we use purrr::map to modify the list column. We want each
  # combination counts only once despite the order, so we use sort.
  mutate(data = map_chr(data, ~paste(sort(.x$item), collapse = ", "))) %>%
  # the last two steps just count the numbers
  group_by(data) %>%
  count()

# A tibble: 21 x 2
# Groups:   data [21]
   data                         n
   <chr>                    <int>
 1 Angie                      336
 2 Angie, Bob                   8
 3 Angie, Bob, Christopher      2
 4 Angie, Bob, Jackie           1
 5 Angie, Christopher          16
 6 Angie, Jackie                9
 7 Angie, Tim                  10
 8 Bob                        331
 9 Bob, Christopher            12
10 Bob, Christopher, Jackie     1
# … with 11 more rows
</code>```

One possible solution

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to aggregate my data to find correlations/patterns, and want to discover how and where data may correlate. Specifically, I want to identify how many times an id (here called 'item') appear together. Is there a way to find how many times each (id) appear together in a row?

This is for a larger data.frame that has already been cleaned and aggregated based on this particular inquiry. In the past, I have tried to apply multiple aggregation, summation and filter functions from packages like 'data.table','dplyr', and 'tidyverse' but cannot quite get what I am looking for.

In section 3(Show some code) I have provided a minimal reproducible example:

set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:12350,2000,replace = T)
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(cbind(number,item), stringsAsFactors = FALSE)

Using the examples here,I expected the output to ID all the combinations where names were aggregated to a number and show the n (value) - expecting results to resemble something like:

Pair       value
Bob, Tim     2
Bob, Jackie  4
Bob, Angie   0

This output (what I am hoping to get) would tell me that in the entire df, there are 2 times that Bob and Tim and 4 times that Bob and Jackie both have the same number.

but the actual output is:

Error: Each row of output must be identified by a unique combination of keys.

Keys are shared for 2000 rows:
* 9, 23, 37, 164, 170, 180, 211...

Update: I thought of a..creative(?) solution - but hope someone can help with expedting it. I can locate all the numbers (column1) that are shared between two names using the following:

x1<-sample_data %>% dplyr::filter(item=="Bob")
x2<-sample_data %>% dplyr::filter(item=="Tim")
Bob<-x1[,1]
Tim<-x2[,1]
Reduce(intersect, list(Bob,Tim))

output:

[1] "12345" "12348" "12350" "12346" "12349" "12347"

Like I said, this is very time consuming and would require creating a plethora of vectors and intersecting each(e.g. 1 vector for each name) and multiple combinations.

Body:
set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:22350,2000,replace = T) # I edited ur number here.
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(cbind(number,item), stringsAsFactors = FALSE)

library(tidyverse)
sample_data %>%
  # find out unique rows
  distinct() %>%
  # nest the data frame into nested tibble, so now you have
  # a "data" column, which is a list of small data frames.
  group_nest(number) %>%
  # Here we use purrr::map to modify the list column. We want each
  # combination counts only once despite the order, so we use sort.
  mutate(data = map_chr(data, ~paste(sort(.x$item), collapse = ", "))) %>%
  # the last two steps just count the numbers
  group_by(data) %>%
  count()

# A tibble: 21 x 2
# Groups:   data [21]
   data                         n
   <chr>                    <int>
 1 Angie                      336
 2 Angie, Bob                   8
 3 Angie, Bob, Christopher      2
 4 Angie, Bob, Jackie           1
 5 Angie, Christopher          16
 6 Angie, Jackie                9
 7 Angie, Tim                  10
 8 Bob                        331
 9 Bob, Christopher            12
10 Bob, Christopher, Jackie     1
# … with 11 more rows

One possible solution


问:
update record value if contains substring from other column
I have two tables, one containing all unique towns names in the UK and another one containing the human-inputted country of residence. Of course humans wrote stuff like "london, uk" or "cardiff, united kingdom".

I need to consolidate the country_of_residence column so I have created a table with all possible towns, counties, cities and villages in the UK with almost 9000 records.

I want to update the column country_of_residence if its records contain any of the record in the column entity in the table uk_geo_entities.

I have read a lot answers here but they all try to update by wanting to check against or update one string, I need to do this against every record of a column.

```<code>a_table                          uk_geo_entities

country_of_residence | ...       entity | ...
-------------------- + ...       ------ + ...
london, uk                       london
cardiff, england                 cardiff

UPDATE a_table
SET country_of_residence = 'united kingdom'
FROM (SELECT entity
      FROM uk_geo_entities) b
WHERE country_of_residence LIKE '%'||b.entity||'%';
</code>```

and

```<code>UPDATE psc_sharing_dodgy_officers
SET country_of_residence = 'united kingdom'
WHERE country_of_residence LIKE '%'||(SELECT entity FROM
uk_geo_entities)||'%';
</code>```

run, but nothing happens.

After a working query I'd need to see

```<code>a_table

country_of_residence | ...
-------------------- + ...
united kingdom
united kingdom
</code>```

答:
You can do it with EXISTS in the WHERE clause:

```<code>UPDATE a_table a
SET country_of_residence = 'united kingdom'
WHERE EXISTS (
  SELECT entity
  FROM uk_geo_entities
  WHERE a.country_of_residence LIKE '%' || entity || '%'
)
</code>```

See the demo.

Body:
I have two tables, one containing all unique towns names in the UK and another one containing the human-inputted country of residence. Of course humans wrote stuff like "london, uk" or "cardiff, united kingdom".

I need to consolidate the country_of_residence column so I have created a table with all possible towns, counties, cities and villages in the UK with almost 9000 records.

I want to update the column country_of_residence if its records contain any of the record in the column entity in the table uk_geo_entities.

I have read a lot answers here but they all try to update by wanting to check against or update one string, I need to do this against every record of a column.

a_table                          uk_geo_entities

country_of_residence | ...       entity | ...
-------------------- + ...       ------ + ...
london, uk                       london
cardiff, england                 cardiff

UPDATE a_table
SET country_of_residence = 'united kingdom'
FROM (SELECT entity
      FROM uk_geo_entities) b
WHERE country_of_residence LIKE '%'||b.entity||'%';

and

UPDATE psc_sharing_dodgy_officers
SET country_of_residence = 'united kingdom'
WHERE country_of_residence LIKE '%'||(SELECT entity FROM
uk_geo_entities)||'%';

run, but nothing happens.

After a working query I'd need to see

a_table

country_of_residence | ...
-------------------- + ...
united kingdom
united kingdom

Body:
You can do it with EXISTS in the WHERE clause:

UPDATE a_table a
SET country_of_residence = 'united kingdom'
WHERE EXISTS (
  SELECT entity
  FROM uk_geo_entities
  WHERE a.country_of_residence LIKE '%' || entity || '%'
)

See the demo.


问:
Angular directive to handle visibility / enabling given a configuration
I have the following directive that handles the visibility / enabling of all child elements starting from the element where it's applied to.

In the ngAfterViewInit, the directive retrieves the configuration of the elements providing to a web API the componentName attribute and the logged user role. Afterwards the config is applied to all the elements that match a row in the configuration.

```<code>import {
  Directive, Input,
  ElementRef, AfterViewInit, ViewContainerRef, Renderer2, DoCheck
} from '@angular/core';
import { CompConfig } from '../model/comp-config';
import { ConfigService } from '../services/config.service';

@Directive({
  selector: '[limsApplyConfig]'
})
export class ApplyConfigDirective implements AfterViewInit, DoCheck {

  config: CompConfig[];
  compName: string;
  constructor(
    private hostElement: ElementRef,
    private cs: ConfigService,
    private renderer: Renderer2
  ) { }

  @Input() set limsApplyConfig(compName: string) {
    this.compName = compName;
  }

  ngAfterViewInit(): void {
    // start with everything hidden: when a config will be received
    // elements can be enabled following configuration
    this.renderer.addClass(this.hostElement.nativeElement, 'cfg-hidden');

    this.cs.getConfig(this.compName).subscribe(c => {
      this.renderer.removeClass(this.hostElement.nativeElement, 'cfg-hidden');
      this.config = c;
      this.config.forEach(cfg => {
        if (this.hostElement.nativeElement.querySelectorAll) {
          const inputCollection = this.hostElement.nativeElement.querySelectorAll('#' + cfg.ControlName);
          inputCollection.forEach(n => {
            // readonly is a property of inputs
            if (n.readOnly !== undefined) {
              n.readOnly = cfg.Disable;
            }
            // disabled is a property of buttons
            if (n.disabled !== undefined) {
              n.disabled = cfg.Disable;
            }
            if (cfg.Invisible) {
              this.renderer.addClass(n, 'cfg-hidden');
            }
          });
        }
      });
    });
  }

  ngDoCheck(): void {
    if (this.config && this.config.length > 0) {
      this.config.forEach(cfg => {
        if (this.hostElement.nativeElement.querySelectorAll) {
          const inputCollection = this.hostElement.nativeElement.querySelectorAll('#' + cfg.ControlName);
          inputCollection.forEach(n => {
            if (n.readOnly !== undefined) {
              n.readOnly = cfg.Disable;
            }
            if (n.disabled !== undefined) {
              n.disabled = cfg.Disable;
            }
            if (cfg.Invisible) {
              this.renderer.addClass(n, 'cfg-hidden');
            }
          });
        }
      });
    }
  }
}
</code>```

For what concerns the enable / disabled status of the elements I'm having difficulties to make the directive win over the specific logic of the component. The config never changes but the status of buttons / inputs does.

In other words, if a button should be disabled, I want to disable it and keep it disabled even if the logic of the component would enable it. Unfortunately I'm not able to do it. I tried adding ngDoCheck life cycle-hook but without any success.

Any help would be appreciated

答:
Directives are evaluated only once until the input changes. If your component is changing the input to the directive [and your component is enabling the button but you still want to disable it via directive then make sure your subscription is executed every time when the input to the directive changes. If my understanding of your problem is correct then let's change the code as follows [please import the necessary classes and pardon for the formatting] -</p>

```<code>    import {
  Directive, Input,
  ElementRef, AfterViewInit, ViewContainerRef, Renderer2, DoCheck
} from '@angular/core';
import { CompConfig } from '../model/comp-config';
import { ConfigService } from '../services/config.service';

@Directive({
  selector: '[limsApplyConfig]'
})
export class ApplyConfigDirective implements AfterViewInit, DoCheck {

  config: CompConfig[];
  compName: string;
  compName$: BehaviorSubject<string>;
  constructor(
    private hostElement: ElementRef,
    private cs: ConfigService,
    private renderer: Renderer2
  ) {
   this.compName$ = new BehaviorSubject<string>(null);
 }

  @Input() set limsApplyConfig(compName: string) {
    this.compName$.next(compName);
  }

  ngAfterViewInit(): void {

    // start with everything hidden: when a config will be received
    // elements can be enabled following configuration
    this.renderer.addClass(this.hostElement.nativeElement, 'cfg-hidden');

    this.compName$
        .pipe(
          mergeMap(cn => this.cs.getConfig(cn)),
          tap(config => {
            this.config.forEach(cfg => {
            if (this.hostElement.nativeElement.querySelectorAll) {
            const inputCollection = this.hostElement.nativeElement.querySelectorAll('#'
            + cfg.ControlName);
          inputCollection.forEach(n => {
            // readonly is a property of inputs
            if (n.readOnly !== undefined) {
              n.readOnly = cfg.Disable;
            }
            // disabled is a property of buttons
            if (n.disabled !== undefined) {
              n.disabled = cfg.Disable;
            }
            if (cfg.Invisible) {
              this.renderer.addClass(n, 'cfg-hidden');
            }
          });
        }
      });
          })
        ).subscribe();

  }
}
</code>```

Body:
I have the following directive that handles the visibility / enabling of all child elements starting from the element where it's applied to.

In the ngAfterViewInit, the directive retrieves the configuration of the elements providing to a web API the componentName attribute and the logged user role. Afterwards the config is applied to all the elements that match a row in the configuration.

import {
  Directive, Input,
  ElementRef, AfterViewInit, ViewContainerRef, Renderer2, DoCheck
} from '@angular/core';
import { CompConfig } from '../model/comp-config';
import { ConfigService } from '../services/config.service';

@Directive({
  selector: '[limsApplyConfig]'
})
export class ApplyConfigDirective implements AfterViewInit, DoCheck {

  config: CompConfig[];
  compName: string;
  constructor(
    private hostElement: ElementRef,
    private cs: ConfigService,
    private renderer: Renderer2
  ) { }

  @Input() set limsApplyConfig(compName: string) {
    this.compName = compName;
  }

  ngAfterViewInit(): void {
    // start with everything hidden: when a config will be received
    // elements can be enabled following configuration
    this.renderer.addClass(this.hostElement.nativeElement, 'cfg-hidden');

    this.cs.getConfig(this.compName).subscribe(c => {
      this.renderer.removeClass(this.hostElement.nativeElement, 'cfg-hidden');
      this.config = c;
      this.config.forEach(cfg => {
        if (this.hostElement.nativeElement.querySelectorAll) {
          const inputCollection = this.hostElement.nativeElement.querySelectorAll('#' + cfg.ControlName);
          inputCollection.forEach(n => {
            // readonly is a property of inputs
            if (n.readOnly !== undefined) {
              n.readOnly = cfg.Disable;
            }
            // disabled is a property of buttons
            if (n.disabled !== undefined) {
              n.disabled = cfg.Disable;
            }
            if (cfg.Invisible) {
              this.renderer.addClass(n, 'cfg-hidden');
            }
          });
        }
      });
    });
  }

  ngDoCheck(): void {
    if (this.config && this.config.length > 0) {
      this.config.forEach(cfg => {
        if (this.hostElement.nativeElement.querySelectorAll) {
          const inputCollection = this.hostElement.nativeElement.querySelectorAll('#' + cfg.ControlName);
          inputCollection.forEach(n => {
            if (n.readOnly !== undefined) {
              n.readOnly = cfg.Disable;
            }
            if (n.disabled !== undefined) {
              n.disabled = cfg.Disable;
            }
            if (cfg.Invisible) {
              this.renderer.addClass(n, 'cfg-hidden');
            }
          });
        }
      });
    }
  }
}

For what concerns the enable / disabled status of the elements I'm having difficulties to make the directive win over the specific logic of the component. The config never changes but the status of buttons / inputs does.

In other words, if a button should be disabled, I want to disable it and keep it disabled even if the logic of the component would enable it. Unfortunately I'm not able to do it. I tried adding ngDoCheck life cycle-hook but without any success.

Any help would be appreciated

Body:
Directives are evaluated only once until the input changes. If your component is changing the input to the directive [and your component is enabling the button but you still want to disable it via directive then make sure your subscription is executed every time when the input to the directive changes. If my understanding of your problem is correct then let's change the code as follows [please import the necessary classes and pardon for the formatting] -

    import {
  Directive, Input,
  ElementRef, AfterViewInit, ViewContainerRef, Renderer2, DoCheck
} from '@angular/core';
import { CompConfig } from '../model/comp-config';
import { ConfigService } from '../services/config.service';

@Directive({
  selector: '[limsApplyConfig]'
})
export class ApplyConfigDirective implements AfterViewInit, DoCheck {

  config: CompConfig[];
  compName: string;
  compName$: BehaviorSubject<string>;
  constructor(
    private hostElement: ElementRef,
    private cs: ConfigService,
    private renderer: Renderer2
  ) {
   this.compName$ = new BehaviorSubject<string>(null);
 }

  @Input() set limsApplyConfig(compName: string) {
    this.compName$.next(compName);
  }

  ngAfterViewInit(): void {

    // start with everything hidden: when a config will be received
    // elements can be enabled following configuration
    this.renderer.addClass(this.hostElement.nativeElement, 'cfg-hidden');

    this.compName$
        .pipe(
          mergeMap(cn => this.cs.getConfig(cn)),
          tap(config => {
            this.config.forEach(cfg => {
            if (this.hostElement.nativeElement.querySelectorAll) {
            const inputCollection = this.hostElement.nativeElement.querySelectorAll('#'
            + cfg.ControlName);
          inputCollection.forEach(n => {
            // readonly is a property of inputs
            if (n.readOnly !== undefined) {
              n.readOnly = cfg.Disable;
            }
            // disabled is a property of buttons
            if (n.disabled !== undefined) {
              n.disabled = cfg.Disable;
            }
            if (cfg.Invisible) {
              this.renderer.addClass(n, 'cfg-hidden');
            }
          });
        }
      });
          })
        ).subscribe();

  }
}


问:
React groupBy and print into table
EDITED:
methods groupBy, omit and mapValue are imported from:

```<code>import groupBy from 'lodash/groupBy';
import mapValues from 'lodash/mapValues';
import omit from 'lodash/omit';
</code>```

I have this json

```<code>[{
    "name": "Jitka",
    "orderNumber": "1",
    "order": false
},
{
    "name": "Jitka",
    "orderNumber": "0",
    "order": false
},
{
    "name": "Petr",
    "orderNumber": "6",
    "order": false
}]
</code>```

In react I need group value by name. And after grouping I need data print into table in format

The problem is, how convert this data, which I groupBy name into table in this format.

My code is:

```<code>{
        const ordersByName = groupBy(this.state && this.state.orders, 'name');
        let order = mapValues(ordersByName, x => x.map(y => omit(y, 'name')));
        this.state.sortedOrders.push(order);

    }

    return (
        <div>
            <MyNavbar/>
            <div className="container">
                <table className="table">
                    <tbody>
                    <tr>
                        <th>Name</th>
                        <th>Order number</th>
                        <th>Order</th>
                    </tr>
                    {this.state.sortedOrders.map((offer) => {
                        console.log(offer);

                    })}
                    </tbody>
                </table>
            </div>
        </div>
</code>```

Thank you.

答:
This solution uses _.flow() to create a combine groups function. The function accepts an iteratee (whatever _.groupBy() can use as iteratee), and a list of keys that should be collected as arrays. The result is a new function that can group by the iteratee, and then merge each group, and combine the values of whatever keys are in collectKeys:

const { flow, partialRight: pr, groupBy, map, mergeWith } = _; // simulates separate imports

const combineGroups = (iteratee, collectKeys) => flow(
  pr(groupBy, iteratee),
  pr(map, group => mergeWith({}, ...group, (t = [], s, k) =>
    collectKeys.includes(k) ? [...t, s] : s)
  )
);

const combineGroupsByName = combineGroups('name', ['orderNumber']);

const Demo = ({ orders }) => {
  const ordersByName = combineGroupsByName(orders);

  return (

                Name
                Order number
                Order

            {ordersByName.map(({ name, orderNumber, order }) => (

                  {name}
                  {orderNumber.sort().join(', ')}
                  {order.toString()}

            ))}

  );
};

const orders = [{"name":"Jitka","orderNumber":"1","order":false},{"name":"Jitka","orderNumber":"0","order":false},{"name":"Petr","orderNumber":"6","order":false}];

ReactDOM.render(
  <Demo orders={orders} />,
  demo
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="demo"></div></code>```

Title: React groupBy and print into table

Body:
EDITED:
methods groupBy, omit and mapValue are imported from:

import groupBy from 'lodash/groupBy';
import mapValues from 'lodash/mapValues';
import omit from 'lodash/omit';

I have this json

[{
    "name": "Jitka",
    "orderNumber": "1",
    "order": false
},
{
    "name": "Jitka",
    "orderNumber": "0",
    "order": false
},
{
    "name": "Petr",
    "orderNumber": "6",
    "order": false
}]

In react I need group value by name. And after grouping I need data print into table in format

The problem is, how convert this data, which I groupBy name into table in this format.

My code is:

{
        const ordersByName = groupBy(this.state && this.state.orders, 'name');
        let order = mapValues(ordersByName, x => x.map(y => omit(y, 'name')));
        this.state.sortedOrders.push(order);

    }

    return (

            <MyNavbar/>

                        Name
                        Order number
                        Order

                    {this.state.sortedOrders.map((offer) => {
                        console.log(offer);

                    })}

Thank you.

Body:
This solution uses _.flow() to create a combine groups function. The function accepts an iteratee (whatever _.groupBy() can use as iteratee), and a list of keys that should be collected as arrays. The result is a new function that can group by the iteratee, and then merge each group, and combine the values of whatever keys are in collectKeys:

const { flow, partialRight: pr, groupBy, map, mergeWith } = _; // simulates separate imports

const combineGroups = (iteratee, collectKeys) => flow(
  pr(groupBy, iteratee),
  pr(map, group => mergeWith({}, ...group, (t = [], s, k) =>
    collectKeys.includes(k) ? [...t, s] : s)
  )
);

const combineGroupsByName = combineGroups('name', ['orderNumber']);

const Demo = ({ orders }) => {
  const ordersByName = combineGroupsByName(orders);

  return (
    <div className="container">
        <table className="table">
            <tbody>
            <tr>
                <th>Name</th>
                <th>Order number</th>
                <th>Order</th>
            </tr>
            {ordersByName.map(({ name, orderNumber, order }) => (
              <tr>
                  <td>{name}</td>
                  <td>{orderNumber.sort().join(', ')}</td>
                  <td>{order.toString()}</td>
              </tr>
            ))}
            </tbody>
        </table>
    </div>
  );
};

const orders = [{"name":"Jitka","orderNumber":"1","order":false},{"name":"Jitka","orderNumber":"0","order":false},{"name":"Petr","orderNumber":"6","order":false}];

ReactDOM.render(
  <Demo orders={orders} />,
  demo
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="demo"></div>


问:
Django ManyToMany model validation
I have a model with a ManyToManyField similar to this one (the model Word has a language, too):

```<code>class Sentence(models.Model):
    words = models.ManyToManyField(Word)
    language = models.ForeignKey(Language)
    def clean(self):
        for word in self.words.all():
            if word.language_id != self.language_id:
                raise ValidationError('One of the words has a false language')
</code>```

When trying to add a new sentence (e.g. through django admin) I get 'Sentence' instance needs to have a primary key value before a many-to-many relationship can be used. This means I can't access self.words before saving it, but this is exactly what I'm trying to do. Is there any way to work around this so you can validate this model nevertheless? I really want to directly validate the model's fields.

I found many questions concerning this exception, but I couldn't find help for my problem. I would appreciate any suggestions!

答:
According to Django docs you can listen to the m2m_changed signal, which will trigger pre_add and post_add actions.

Using add() with a many-to-many relationship, however, will not call any save() methods (the bulk argument doesn’t exist), but rather create the relationships using QuerySet.bulk_create(). If you need to execute some custom logic when a relationship is created, listen to the m2m_changed signal, which will trigger pre_add and post_add actions.

ContentLicense: CC BY-SA 3.0

Title: Django ManyToMany model validation

Body:
I have a model with a ManyToManyField similar to this one (the model Word has a language, too):

class Sentence(models.Model):
    words = models.ManyToManyField(Word)
    language = models.ForeignKey(Language)
    def clean(self):
        for word in self.words.all():
            if word.language_id != self.language_id:
                raise ValidationError('One of the words has a false language')

When trying to add a new sentence (e.g. through django admin) I get 'Sentence' instance needs to have a primary key value before a many-to-many relationship can be used. This means I can't access self.words before saving it, but this is exactly what I'm trying to do. Is there any way to work around this so you can validate this model nevertheless? I really want to directly validate the model's fields.

I found many questions concerning this exception, but I couldn't find help for my problem. I would appreciate any suggestions!


问:
Best method to determine if viewport or 'standard' browser
So, by now we all know that iOS mobile Safari uses viewports (as does Android browser), rather than a 'standard' browser window. And this causes issues with overflow:hidden, and position:fixed.

This unfortunately is the same case with the iPad. I presume this is the case for other Android tablets too.

Rather than browser sniffing each time, is there an easy way to determine if the browser has a viewport or if it is standard?

答:
Try media queries: you can include stylesheets, or apply parts of a stylesheet conditionally, based on the device and viewport dimensions the browser reports.

This article gives a decent enough introduction: http://www.alistapart.com/articles/responsive-web-design/


问:
Is there a "theirs" version of "git merge -s ours"?
When merging topic branch "B" into "A" using git merge, I get some conflicts. I know all the conflicts can be solved using the version in "B".

I am aware of git merge -s ours. But what I want is something like git merge -s theirs.

Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing git commands? (git checkout every unmerged file from B)

The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.

答:
This answer was given by Paul Pladijs. I just took his commands and made a git alias for convenience.

Edit your .gitconfig and add the following:

```<code>[alias]
    mergetheirs = "!git merge -s ours \"$1\" && git branch temp_THEIRS && git reset --hard \"$1\" && git reset --soft temp_THEIRS && git commit --amend && git branch -D temp_THEIRS"
</code>```

Then you can "git merge -s theirs A" by running:

```<code>git checkout B (optional, just making sure we're on branch B)
git mergetheirs A
</code>```

OwnerDisplayName: elmarco

Body:
This answer was given by Paul Pladijs. I just took his commands and made a git alias for convenience.

Edit your .gitconfig and add the following:

[alias]
    mergetheirs = "!git merge -s ours \"$1\" && git branch temp_THEIRS && git reset --hard \"$1\" && git reset --soft temp_THEIRS && git commit --amend && git branch -D temp_THEIRS"

Then you can "git merge -s theirs A" by running:

git checkout B (optional, just making sure we're on branch B)
git mergetheirs A


问:
Deducing the template parameter of a templated class argument: const issue
I think the problem is fairly common, so there should be a known solution. I came up with one, but I'm not really satisfied, so I'm asking here, hoping someone can help.

Say I have a function, whose signature is

```<code>template<typename T>
void foo(const MyArray<const T>& x);
</code>```

The const in the template parameter is to prevent me from changin the array content, since (for reasons beyond this question), the accessors ([] and ()) of MyArray<T> are always marked const, and return references to T (hence, the const ensure safety, since MyArray<T>::operator[] returns T&, while MyArray<const T>::operator[] returns const T&).

Great. However, templates with different template arguments are non related, so I can't bind a reference to MyClass<T> to a reference of MyClass<const T>, meaning I can't do this

```<code>MyArray<double> ar(/*blah*/);
foo(ar);
</code>```

Notice that, without a reference, the code above would work provided that there is a copy constructor that lets me create MyArray<const T> from MyArray<T>. However, I don't want to remove the reference, since the array construction would happen a lot of times, and, despite relatively cheap, its cost would add up.

So the question: how can I call foo with an MyArray<T>?

My only solution so far is the following:

```<code>MyArray<T> ar(/*blah*/);
foo(reinterpret_cast<MyArray<const T>>(ar));
</code>```

(actually in my code I hid the reinterpret cast in an inlined function with more verbose name, but the end game is the same). The class MyArray does not have a specialization for const T that makes it not reinterpretable, so the cast should be 'safe'. But this is not really a nice solution to read. An alternative, would be to duplicate foo's signature, to have a version taking MyArray<T>, which implementation does the cast and calls the const version. The problem with this is code duplication (and I have quite a few functions foo that need to be duplicated).

Perhaps some extra template magic on the signature of foo? The goal is to pass both MyArray<T> and MyArray<const T>, while still retaining const-correctness (i.e., make the compiler bark if I accidentally change the input in the function body).

Edit 1: The class MyArray (whose implementation is not under my control), has const accessors, since it stores pointers. So calling v[3] will modify the values in the array, but not the members stored in the class (namely a pointer and some smart-pointer-like metadata). In other words, the object is de facto not modified by accessors, though the array is. It's a semantic distinction. Not sure why they went this direction (I have an idea, but too long to explain).

Edit 2: I accepted one of the two answers (though they were somewhat similar). I am not sure (for reasons long to explain) that the wrapper class is doable in my case (maybe, I have to think about it). I am also puzzled by the fact that, while

```<code>template<typename T>
void foo(const MyArray<const T>& x);
MyArray<int> a;
foo(a);
</code>```

does not compile, the following does

```<code>void foo(const MyArray<const int>& x);
MyArray<int> a;
foo(a);
</code>```

Note: MyArray does offer a templated "copy constructor" with signature

```<code>template<typename S>
MyArray(const MyArray<S>&);
</code>```

so it can create MyArray<const T> from MyArray<T>. I am puzzled why it works when T is explicit, while it doesn't if T is a template parameter.

答:
I would stay with

```<code>template<typename T>
void foo(const MyArray<T>&);
</code>```

and make sure to instantiate it with const T (in unitTest for example).

Else you can create a view as std::span.

Something like (Depending of other methods provided by MyArray, you probably can do a better const view. I currently only used operator[]):

```<code>template <typename T>
struct MyArrayConstView
{
    MyArrayConstView(MyArray<T>& array) : mArray(std::ref(array)) {}
    MyArrayConstView(MyArray<const T>& array) : mArray(std::ref(array)) {}

    const T& operator[](std::size_t i) {
        return std::visit([i](const auto& a) -> const T& { return a[i]; }), mArray);
    }

private:
    std::variant<std::reference_wrapper<MyArray<T>>,
                 std::reference_wrapper<MyArray<const T>>> mArray;
};
</code>```

and then

```<code>template <typename T>
void foo(const MyArrayConstView<T>&);
</code>```

but you need to call it explicitly, (as deduction won't happen as MyArray<T> is not a MyArrayConstView)

```<code>MyArray<double> ar(/*blah*/);
foo(MyArrayConstView{ar});
foo<double>(ar);
</code>```

Body:
I think the problem is fairly common, so there should be a known solution. I came up with one, but I'm not really satisfied, so I'm asking here, hoping someone can help.

Say I have a function, whose signature is

template<typename T>
void foo(const MyArray<const T>& x);

The const in the template parameter is to prevent me from changin the array content, since (for reasons beyond this question), the accessors ([] and ()) of MyArray<T> are always marked const, and return references to T (hence, the const ensure safety, since MyArray<T>::operator[] returns T&, while MyArray<const T>::operator[] returns const T&).

Great. However, templates with different template arguments are non related, so I can't bind a reference to MyClass<T> to a reference of MyClass<const T>, meaning I can't do this

MyArray<double> ar(/*blah*/);
foo(ar);

Notice that, without a reference, the code above would work provided that there is a copy constructor that lets me create MyArray<const T> from MyArray<T>. However, I don't want to remove the reference, since the array construction would happen a lot of times, and, despite relatively cheap, its cost would add up.

So the question: how can I call foo with an MyArray<T>?

My only solution so far is the following:

MyArray<T> ar(/*blah*/);
foo(reinterpret_cast<MyArray<const T>>(ar));

(actually in my code I hid the reinterpret cast in an inlined function with more verbose name, but the end game is the same). The class MyArray does not have a specialization for const T that makes it not reinterpretable, so the cast should be 'safe'. But this is not really a nice solution to read. An alternative, would be to duplicate foo's signature, to have a version taking MyArray<T>, which implementation does the cast and calls the const version. The problem with this is code duplication (and I have quite a few functions foo that need to be duplicated).

Perhaps some extra template magic on the signature of foo? The goal is to pass both MyArray<T> and MyArray<const T>, while still retaining const-correctness (i.e., make the compiler bark if I accidentally change the input in the function body).

Edit 1: The class MyArray (whose implementation is not under my control), has const accessors, since it stores pointers. So calling v[3] will modify the values in the array, but not the members stored in the class (namely a pointer and some smart-pointer-like metadata). In other words, the object is de facto not modified by accessors, though the array is. It's a semantic distinction. Not sure why they went this direction (I have an idea, but too long to explain).

Edit 2: I accepted one of the two answers (though they were somewhat similar). I am not sure (for reasons long to explain) that the wrapper class is doable in my case (maybe, I have to think about it). I am also puzzled by the fact that, while

template<typename T>
void foo(const MyArray<const T>& x);
MyArray<int> a;
foo(a);

does not compile, the following does

void foo(const MyArray<const int>& x);
MyArray<int> a;
foo(a);

Note: MyArray does offer a templated "copy constructor" with signature

template<typename S>
MyArray(const MyArray<S>&);

so it can create MyArray<const T> from MyArray<T>. I am puzzled why it works when T is explicit, while it doesn't if T is a template parameter.

Body:
I would stay with

template<typename T>
void foo(const MyArray<T>&);

and make sure to instantiate it with const T (in unitTest for example).

Else you can create a view as std::span.

Something like (Depending of other methods provided by MyArray, you probably can do a better const view. I currently only used operator[]):

template <typename T>
struct MyArrayConstView
{
    MyArrayConstView(MyArray<T>& array) : mArray(std::ref(array)) {}
    MyArrayConstView(MyArray<const T>& array) : mArray(std::ref(array)) {}

    const T& operator[](std::size_t i) {
        return std::visit([i](const auto& a) -> const T& { return a[i]; }), mArray);
    }

private:
    std::variant<std::reference_wrapper<MyArray<T>>,
                 std::reference_wrapper<MyArray<const T>>> mArray;
};

and then

template <typename T>
void foo(const MyArrayConstView<T>&);

but you need to call it explicitly, (as deduction won't happen as MyArray<T> is not a MyArrayConstView)

MyArray<double> ar(/*blah*/);
foo(MyArrayConstView{ar});
foo<double>(ar);


问:
SELECT query where two fields do NOT match not working
I have an VBA script which looks through a table that is a join of two different tables (a and b), where there may be fields that don't match between the table (table a is the original, table b is the same table, but a new export file).

The goal is to find which field(s) differ and update one field in the shared field with a list of fields that did not match between the two tables (a and b).

But one field is not passing its test.  I tried separately querying this table to see if I could use a simple SQL query to determine if Access was recognizing the difference.

I cannot understand why this is not working, as if I try other fields in the same manner, it returns the expected result.  I have confirmed that both fields are Short Text data type, both fields have the same "General Properties", "Lookup Properties" and the "Property Sheet" also matches not only between the two fields, but all other similar fields.

This query:

```<code>SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE ID = 18;
</code>```

Results in:

```<code>[a_Address 2] = (NULL)
[b_Address 2] = xasdf
</code>```

But when I try this query:

```<code>SELECT *
FROM Staging_LOG_ExportDifferences
WHERE [a_Address 2] <> [b_Address 2];
</code>```

Results in:

```<code>No results
</code>```

答:
This is the semantics of NULL.  It fails almost every comparison -- or more accurately, the comparison returns NULL which is filtered out along with FALSE.

Standard SQL has a NULL-safe comparison, IS DISTINCT FROM.  But MS Access doesn't support it.

So, you can be explicit:

```<code>SELECT *
FROM Staging_LOG_ExportDifferences
WHERE ([a_Address 2] <> [b_Address 2]) OR
      ([a_Address 2] IS NULL AND [b_Address 2] IS NOT NULL) OR
      ([a_Address 2] IS NOT NULL AND [b_Address 2] IS NULL) ;
</code>```

Body:
I have an VBA script which looks through a table that is a join of two different tables (a and b), where there may be fields that don't match between the table (table a is the original, table b is the same table, but a new export file).

The goal is to find which field(s) differ and update one field in the shared field with a list of fields that did not match between the two tables (a and b).

But one field is not passing its test.  I tried separately querying this table to see if I could use a simple SQL query to determine if Access was recognizing the difference.

I cannot understand why this is not working, as if I try other fields in the same manner, it returns the expected result.  I have confirmed that both fields are Short Text data type, both fields have the same "General Properties", "Lookup Properties" and the "Property Sheet" also matches not only between the two fields, but all other similar fields.

This query:

SELECT [a_Address 2], [b_Address 2]
FROM Staging_LOG_ExportDifferences
WHERE ID = 18;

Results in:

[a_Address 2] = (NULL)
[b_Address 2] = xasdf

But when I try this query:

SELECT *
FROM Staging_LOG_ExportDifferences
WHERE [a_Address 2] <> [b_Address 2];

Results in:

No results

Body:
This is the semantics of NULL.  It fails almost every comparison -- or more accurately, the comparison returns NULL which is filtered out along with FALSE.

Standard SQL has a NULL-safe comparison, IS DISTINCT FROM.  But MS Access doesn't support it.

So, you can be explicit:

SELECT *
FROM Staging_LOG_ExportDifferences
WHERE ([a_Address 2] <> [b_Address 2]) OR
      ([a_Address 2] IS NULL AND [b_Address 2] IS NOT NULL) OR
      ([a_Address 2] IS NOT NULL AND [b_Address 2] IS NULL) ;


问:
Foreach message in logstash
I need help, I want to compare 2 or more messages containce kv in logstash

examples :

first message :  X < 10=5.4|9=14|36=V|3=9|49=360T_SEP|5=Good|220=p48

second messages : y1 > 8=pap4|10=495|37=d|34=7|49=SEP|220=p48
                  y2 > 8=pap4|10=495|34=d|34=7|49=SEP|220=p48

iteration 1 : I get two key : 5 and 220
iteration 2 : I check if y1 has not 5 and 220 from x equals 220 to y1 then set in y1 5.

Basically, I want retrieved in each message the key 220 which corresponds to 5

Any Suggestion please.

答:
Unless things have really changed, logstash typically concerns itself with one event at a time.  The elapsed filter is one of the only exception where it is considering prior events in the processing.

You could use ruby to create your own cache, or perhaps use the redis inputs and outputs to that effect, but I'd suggest changing the format of the original message to include the data you need.

Title: Foreach message in logstash


问:
How to setState to answer from APi and use map
Im trying to create recipes searcher. In App.js I receive query from search input from another component and I want to setState to answer from APi. Console.log from  callback in setState shows updated state but the state is not updated. I need setState updaed so I can use map on it and display list of recipes in render. It gives me error map is not a function because this.state.recipesList is still empty. Anyone can help me ?

```<code>class App extends Component {
  state = {
    query: "",
    recipesList: []
  };

  getQuery = query => {
    const key = "2889f0d3f51281eea62fa6726e16991e";
    const URL = `https://www.food2fork.com/api/search?key=${key}&q=${query}`;

    fetch(URL)
      .then(res => res.json())
      .then(res => {
        this.setState(
          {
            recipesList: res
          },
          () => {
            console.log(this.state.recipesList);
          }
        );
      });
    console.log(this.state.recipesList);
  };
  render() {
     const test = this.state.recipesList.map(item => {
       return (
         <div className="recispesList">
           <h1>{item.title}</h1>
        </div>
       );
     });

    return (
      <div className="App">
        <Search query={this.getQuery} />
        <div className="contentWrapper">{}</div>
      </div>
    );
  }
}
</code>```

Search component:

```<code>class Search extends Component {
  state = {
    searchValue: ""
  };

  handleChange = val => {
    let searchValue = val.target.value;
    this.setState({
      searchValue
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      searchValue: ""
    });
    this.props.query(this.state.searchValue);
  };
  render() {
    return (
      <div className="searchWrapper">
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.handleChange} value={this.state.searchValue} />
          <button />
        </form>
      </div>
    );
  }
}

export default Search;
</code>```

答:
It seems that instead of directly assigning the whole response to recipesList:

```<code>this.setState(
  {
    recipesList: res
  },
  () => {
    console.log(this.state.recipesList);
  }
);
</code>```

you need to get recipes array first via res.recipes:

```<code>this.setState(
  {
    recipesList: res.recipes
  },
  () => {
    console.log(this.state.recipesList);
  }
);
</code>```

Body:
Im trying to create recipes searcher. In App.js I receive query from search input from another component and I want to setState to answer from APi. Console.log from  callback in setState shows updated state but the state is not updated. I need setState updaed so I can use map on it and display list of recipes in render. It gives me error map is not a function because this.state.recipesList is still empty. Anyone can help me ?

class App extends Component {
  state = {
    query: "",
    recipesList: []
  };

  getQuery = query => {
    const key = "2889f0d3f51281eea62fa6726e16991e";
    const URL = `https://www.food2fork.com/api/search?key=${key}&q=${query}`;

    fetch(URL)
      .then(res => res.json())
      .then(res => {
        this.setState(
          {
            recipesList: res
          },
          () => {
            console.log(this.state.recipesList);
          }
        );
      });
    console.log(this.state.recipesList);
  };
  render() {
     const test = this.state.recipesList.map(item => {
       return (

{item.title}

       );
     });

    return (

        <Search query={this.getQuery} />

{}

    );
  }
}

Search component:

class Search extends Component {
  state = {
    searchValue: ""
  };

  handleChange = val => {
    let searchValue = val.target.value;
    this.setState({
      searchValue
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      searchValue: ""
    });
    this.props.query(this.state.searchValue);
  };
  render() {
    return (

        <form onSubmit={this.handleSubmit}>
          <input onChange={this.handleChange} value={this.state.searchValue} />
          <button />
        </form>

    );
  }
}

export default Search;

Body:
It seems that instead of directly assigning the whole response to recipesList:

this.setState(
  {
    recipesList: res
  },
  () => {
    console.log(this.state.recipesList);
  }
);

you need to get recipes array first via res.recipes:

this.setState(
  {
    recipesList: res.recipes
  },
  () => {
    console.log(this.state.recipesList);
  }
);


问:
JavaScript: filter() Method Returning Back Original Array and Not Filtering
I have the following code below using the filter() array function.

arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

console.log(test(arr))```

My code is returning the original array ([ 12, 5, 8, 130, 44 ]) and not filtering at all.  What am I doing wrong?

Note: I want to use the filter() method for this.

答:
Filter returns a new array, so depending on how you are using your function, you most likely are looking at the original array, which you cannot do, you need to look at the filtered results.

let arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

// The filtered results
console.log('The filtered array', test(arr))

// The original array
console.log('The original array', arr)```
</div>
</div>
</p>

<p>To modify the array in place you can use a while loop, and then splice the elements like this which will modify the array in place.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [12, 5, 8, 130, 44]

// Get the initial length of the array
let i = arr.length

// Loop backwards over the array as not to skip values when they get removed
while(--i) {
  if(arr[i] > 10) continue
  arr.splice(i, 1)
}

console.log(arr)</code>```

Instead of a while, you could also just assign the value back to the original array overwriting is original value.

let arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

// Assign the result back to arr
arr = test(arr)

// The new value of arr
console.log(arr)```

Body:
I have the following code below using the filter() array function.

arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

console.log(test(arr))

My code is returning the original array ([ 12, 5, 8, 130, 44 ]) and not filtering at all.  What am I doing wrong?

Note: I want to use the filter() method for this.

Body:
Filter returns a new array, so depending on how you are using your function, you most likely are looking at the original array, which you cannot do, you need to look at the filtered results.

let arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

// The filtered results
console.log('The filtered array', test(arr))

// The original array
console.log('The original array', arr)

To modify the array in place you can use a while loop, and then splice the elements like this which will modify the array in place.

let arr = [12, 5, 8, 130, 44]

// Get the initial length of the array
let i = arr.length

// Loop backwards over the array as not to skip values when they get removed
while(--i) {
  if(arr[i] > 10) continue
  arr.splice(i, 1)
}

console.log(arr)

Instead of a while, you could also just assign the value back to the original array overwriting is original value.

let arr = [12, 5, 8, 130, 44]

function test(arr) {
  return arr.filter((element) => {
    return element >= 10
  });
}

// Assign the result back to arr
arr = test(arr)

// The new value of arr
console.log(arr)


问:
Why does my android app only work in flight mode?
I created an app in Android studio using maps and geo location with great success.  I've recently updated my phone handset (Samsung J6 Plus) to Pie 9.0 but now the app will not load on my phone or on the virtual device within Android studio.  It will load however, when my phone and the virtual device is set to flight mode.

I've updated Android studio to 3.4.1 and updated the support repository SDK Tools, SDK Platform-Tools, Emulator and SDK build-tools 29-rc3.

```<code>import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

//Changed from Stackflow - public class AR_MapsActivity extends FragmentActivity implements OnMapReadyCallback
public class AR_MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu, menu);

            return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    private GoogleMap mMap;

    LocationListener locationListener;
    LocationManager locationManager;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) ;
            {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    ;
                {
                    locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 30, 5, locationListener);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ar_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        //RM Adding the code from the location activity Lecture 97 LocationManager and listener
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                //Added a Toast - for demo and then added the code for the location
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                // Add a marker in Sydney and move the camera
                LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));

                //Added 06-03-2019 to add another pointer on map
                LatLng randy = new LatLng(50.877644, -2.108941);
                mMap.addMarker(new MarkerOptions().position(randy).title("Randy HQ"));

                LatLng roddy = new LatLng(50.876722, -2.101839);
                mMap.addMarker(new MarkerOptions().position(roddy).title("Roddy HQ"));
                //Hardcoded another pointer on the map

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        //RM - Adding code from location activity
        //RM - WAS - if (Build.VERSION.SDK_INT < 28)

        if (Build.VERSION.SDK_INT < 28)
        {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);
        } else {

            //RM - Checks for permission from phone
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                 else    {

                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);

                    Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);

                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

                LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                mMap.clear();

                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));
                }
            }
    }
}
</code>```

The app will prompt to request location but then crash out, the message will then say that the App keeps stopping.  This is the same on my phone and virtual emulator, which is set on Pie 9.0 API 28.  However the app will load when airline mode is selected but as this is a map based app it will not display the map.

答:
Thanks, I added the code after</p>

```<code></activity>

<uses-library
  android:name="org.apache.http.legacy"
  android:required="false" />

</application>
</code>```

Body:
I created an app in Android studio using maps and geo location with great success.  I've recently updated my phone handset (Samsung J6 Plus) to Pie 9.0 but now the app will not load on my phone or on the virtual device within Android studio.  It will load however, when my phone and the virtual device is set to flight mode.

I've updated Android studio to 3.4.1 and updated the support repository SDK Tools, SDK Platform-Tools, Emulator and SDK build-tools 29-rc3.

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

//Changed from Stackflow - public class AR_MapsActivity extends FragmentActivity implements OnMapReadyCallback
public class AR_MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu, menu);

            return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    private GoogleMap mMap;

    LocationListener locationListener;
    LocationManager locationManager;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) ;
            {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    ;
                {
                    locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 30, 5, locationListener);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ar_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        //RM Adding the code from the location activity Lecture 97 LocationManager and listener
        locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                //Added a Toast - for demo and then added the code for the location
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                // Add a marker in Sydney and move the camera
                LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));

                //Added 06-03-2019 to add another pointer on map
                LatLng randy = new LatLng(50.877644, -2.108941);
                mMap.addMarker(new MarkerOptions().position(randy).title("Randy HQ"));

                LatLng roddy = new LatLng(50.876722, -2.101839);
                mMap.addMarker(new MarkerOptions().position(roddy).title("Roddy HQ"));
                //Hardcoded another pointer on the map

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        //RM - Adding code from location activity
        //RM - WAS - if (Build.VERSION.SDK_INT < 28)

        if (Build.VERSION.SDK_INT < 28)
        {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);
        } else {

            //RM - Checks for permission from phone
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                 else    {

                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 5, locationListener);

                    Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);

                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

                LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                mMap.clear();

                mMap.addMarker(new MarkerOptions().position(userLocation).title("AR Projects HQ"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 16));
                }
            }
    }
}

The app will prompt to request location but then crash out, the message will then say that the App keeps stopping.  This is the same on my phone and virtual emulator, which is set on Pie 9.0 API 28.  However the app will load when airline mode is selected but as this is a map based app it will not display the map.

Body:
Thanks, I added the code after

</activity>

<uses-library
  android:name="org.apache.http.legacy"
  android:required="false" />

</application>


问:
Url rewrite 2.1 stops Application pool in IIS 8.5 (return 503 status), windows server 2012R2
I install the URL Rewrite from the Web Platform Installer.
No added rule.
Then, when I access website url, it returned 503 code and Application Pool was stopped.
It works normally when I uninstall the URL rewrite module from Control Panel.

I have tried many searches on google but no results.

I found that in Event log:
- The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load. The data is the error. Application pool 'DefaultAppPool' is being automatically disabled due to a series of failures in the process(es) serving that application pool.
(rewrite.dll is exits)

Any ideas?

答:
In event log I found the same message. I.e. The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load. The data is the error.

For me the solution that worked was to replace the "rewrite.dll". In 2 of our other server it was working fine and they were installed in 2017. So I just copied the "rewrite.dll" from that server and replace it on my new server.

For me the older version(v7.1.1952.0) of the dll works, but new version ( v7.1.1993.2351), which comes with the latest setup, doesn't work.

BTW you need to stop the IIS before you replace the dll and start again.


问:
NuSMV CTL specification
I have started learning NuSMV these days. I have this code:

```<code> MODULE main

 VAR

 state: {a,b,c,d,e};
 ASSIGN

 init(state) := a;

 next(state) := case

            (state = a)  : b;

            (state = b)  : c;

            (state = c)  : d;

            (state = d)  : e;

            TRUE:Stages;

       esac;
</code>```

I want to verify that every time we are in the state "a" the next state will be the state "b". which one is the correct (even if I tried both of them and  they give me both of them true):

```<code>check_ctlspec -p "AG (state=a -> AX state=b)"

check_ctlspec -p "AF (state=a -> AX state=b)"

check_ctlspec -p "AF (state=a -> AF state=b)"

check_ctlspec -p "AF (state=a -> state=b)"
</code>```

My second question is: In the model above there is no a transition from the state "d" to the state "a" but when I verify this using

```<code>check_ctlspec -p "AF (state=d -> AX state=a)"
</code>```

the result was true. Why is this the case?

答:
First of all, let me rename state with my_var in your model. This avoids confusing the actual state of the automaton with the state variable you have introduced.

AG (my_var = a -> AX my_var = b)

In every state of every possible execution, if my_var is equal to a then it must be necessarily the case that in the next statemy_var is equal to b.

This is the property you want to verify.

AF (my_var=a -> AX my_var=b)

Sooner or later, if my_var is equal to a then it must be necessarily the case that in the next statemy_var is equal to b.

Notice that an implication is true in two cases:

when the premise is true and the conclusion is true, or

when the premise is false

So the implication is trivially made true by any state for which the premise my_var=a is not verified, that is, any state other than the initial state. Since you use AF, you require the implication to be verified only on (at least) one state for each possible execution path.

In a sense, this is "too weak" with respect to what you want to verify.

AF (my_var=a -> AF my_var=b)

Sooner or later, if my_var is equal to a then it must be necessarily the case at some point in the future (wrt. the state in which my_var is equal to a) my_var becomes equal to b.

Similar as previous one, this is even weaker because it does not even specify at what point my_var becomes equal to b.

AF (my_var=a -> my_var=b)

Notice that the implication (my_var=a -> my_var=b) is only true when my_var=a is false, because my_var cannot be con-temporarily assigned to both a and b. Nevertheless, this condition is verified by any state other than the initial state, so again the property is trivially verified.

AF (my_var=d -> AX my_var=a)

Again, this condition is too weak because you are using AF and not AG. The implication is made true by any state for which my_var != d, so it is sufficient for the whole property to be verified.

I would invite you to take a look to this stack-overflow Q/A or to these slides for learning more about the tool and the language.

Title: NuSMV CTL specification

Body:
I have started learning NuSMV these days. I have this code:

 MODULE main

 VAR

 state: {a,b,c,d,e};
 ASSIGN

 init(state) := a;

 next(state) := case

            (state = a)  : b;

            (state = b)  : c;

            (state = c)  : d;

            (state = d)  : e;

            TRUE:Stages;

       esac;

I want to verify that every time we are in the state "a" the next state will be the state "b". which one is the correct (even if I tried both of them and  they give me both of them true):

check_ctlspec -p "AG (state=a -> AX state=b)"

check_ctlspec -p "AF (state=a -> AX state=b)"

check_ctlspec -p "AF (state=a -> AF state=b)"

check_ctlspec -p "AF (state=a -> state=b)"

My second question is: In the model above there is no a transition from the state "d" to the state "a" but when I verify this using

check_ctlspec -p "AF (state=d -> AX state=a)"

the result was true. Why is this the case?


问:
How to format pattern text export in Powershell
I'm creating an powershell script to format .txt files and eventually be converted to a csv file (unless this can be done together). I've dug through quite a few other questions but haven't been able to figure it out. Every time I run the script below it selects all the data I need but puts it altogether on one line.

```<code>$importPath = 'C:\Example.txt'
$pattern = "<return>(.*?)</return>"

$string = Get-Content $importPath
$result = [regex]::match($string, $pattern).Groups[1].Value
$result | Out-File -FilePath 'C:\ResponseOnly.txt'
</code>```

I'd appreciate some help in figuring a way to get all the information between the <return> and </return> but still having all the data broken out on the original rows.

Example of source file:

```<code>Status: OK
Time Taken: 193
Size: 46511
Timestamp: Thu May 30 03:39:37 MDT 2019
TestStep: getReportResultCsv

----------------- Messages ------------------------------

----------------- Properties ------------------------------
Endpoint: XXXXXXXXXXXXXXXXXXXXXXX
Username: XXXXXXXXXXXXXXXXXXXXXXX
domain: XXXXXXXXXXXXXXXXXXXXXXX HTTP/1.1
Encoding: UTF-8
Password: XXXXXXXXXXXXXXXXXXXXXXX

---------------- Request ---------------------------
Request Headers: SOAPAction : ""
Authorization : Basic XXXXXXXXXXXXXXXXXXXXXXX
Connection : Keep-Alive
User-Agent : Apache-HttpClient/4.1.1 (java 1.5)
Host : XXXXXXXXXXXXXXXXXXXXXXX
Accept-Encoding : gzip,deflate
Content-Length : 378
Content-Type : text/xml;charset=UTF-8

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="XXXXXXXXXXXXXXXXXXXXXXX">
  <soapenv:Header/>
   <soapenv:Body>
      <ser:getReportResultCsv>
         <!--Optional:-->
         <identifier>A0294584B2F933513rt0.c.ie.oF0BBB@5p70B7FsBlEf4v490cAm</identifier>
      </ser:getReportResultCsv>
   </soapenv:Body>
</soapenv:Envelope>

---------------- Response --------------------------
Response Headers: Transfer-Encoding : chunked
Server : nginx
Access-Control-Allow-Origin : *
Access-Control-Allow-Methods : POST,GET,OPTIONS
Connection : keep-alive
Content-Encoding : gzip
Set-Cookie : clientId=XXXXXXXXXXXXXXXXXXXXXXX
#status# : HTTP/1.1 200 OK
Date : Thu, 30 May 2019 09:39:37 GMT
Content-Type : text/xml;charset=UTF-8

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <ns2:getReportResultCsvResponse xmlns:ns2="XXXXXXXXXXXXXXXXXXXXXXX">
         <return>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44</return>
      </ns2:getReportResultCsvResponse>
   </env:Body>
</env:Envelope>
</code>```

Example of how file should be:

```<code>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44
</code>```

答:
This is easier then you expect, since what you have for input is XML. Try this:

```<code>$importPath = 'C:\Example.txt'
[xml]$DataIn=Get-Content $importPath
$DataIn.Envelope.Body.getReportResultCsvResponse.return| Out-File -FilePath 'C:\ResponseOnly.txt'
</code>```

That will just get you what you're looking for.

If you really want to use RegEx, I would read the whole file in as a multiline string, and match against that to get your output. You just need to tell the RegEx that you're going against a multiline string when you do it.

```<code>$pattern = "(?ms)<return>(.*?)</return>"
$string = Get-Content $importPath -raw
$result = [regex]::match($string, $pattern).Groups[1].Value
$result | Out-File -FilePath 'C:\ResponseOnly.txt'
</code>```

Body:
I'm creating an powershell script to format .txt files and eventually be converted to a csv file (unless this can be done together). I've dug through quite a few other questions but haven't been able to figure it out. Every time I run the script below it selects all the data I need but puts it altogether on one line.

$importPath = 'C:\Example.txt'
$pattern = "<return>(.*?)</return>"

$string = Get-Content $importPath
$result = [regex]::match($string, $pattern).Groups[1].Value
$result | Out-File -FilePath 'C:\ResponseOnly.txt'

I'd appreciate some help in figuring a way to get all the information between the <return> and </return> but still having all the data broken out on the original rows.

Example of source file:

Status: OK
Time Taken: 193
Size: 46511
Timestamp: Thu May 30 03:39:37 MDT 2019
TestStep: getReportResultCsv

----------------- Messages ------------------------------

----------------- Properties ------------------------------
Endpoint: XXXXXXXXXXXXXXXXXXXXXXX
Username: XXXXXXXXXXXXXXXXXXXXXXX
domain: XXXXXXXXXXXXXXXXXXXXXXX HTTP/1.1
Encoding: UTF-8
Password: XXXXXXXXXXXXXXXXXXXXXXX

---------------- Request ---------------------------
Request Headers: SOAPAction : ""
Authorization : Basic XXXXXXXXXXXXXXXXXXXXXXX
Connection : Keep-Alive
User-Agent : Apache-HttpClient/4.1.1 (java 1.5)
Host : XXXXXXXXXXXXXXXXXXXXXXX
Accept-Encoding : gzip,deflate
Content-Length : 378
Content-Type : text/xml;charset=UTF-8

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="XXXXXXXXXXXXXXXXXXXXXXX">
  <soapenv:Header/>
   <soapenv:Body>
      <ser:getReportResultCsv>

         <identifier>A0294584B2F933513rt0.c.ie.oF0BBB@5p70B7FsBlEf4v490cAm</identifier>
      </ser:getReportResultCsv>
   </soapenv:Body>
</soapenv:Envelope>

---------------- Response --------------------------
Response Headers: Transfer-Encoding : chunked
Server : nginx
Access-Control-Allow-Origin : *
Access-Control-Allow-Methods : POST,GET,OPTIONS
Connection : keep-alive
Content-Encoding : gzip
Set-Cookie : clientId=XXXXXXXXXXXXXXXXXXXXXXX
#status# : HTTP/1.1 200 OK
Date : Thu, 30 May 2019 09:39:37 GMT
Content-Type : text/xml;charset=UTF-8

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <ns2:getReportResultCsvResponse xmlns:ns2="XXXXXXXXXXXXXXXXXXXXXXX">
         <return>DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44</return>
      </ns2:getReportResultCsvResponse>
   </env:Body>
</env:Envelope>

Example of how file should be:

DATE,AGENT GROUP,AGENT NAME,CALLS,HANDLE TIME,Average HANDLE TIME,HOLD TIME,Average HOLD TIME,Average AFTER CALL WORK TIME
2019/04/04,Billy Bob,Joe Joseph,6,04:15:53,00:42:39,00:00:00,00:00:00,00:01:55
2019/04/05,Billy Bob,Joe Joseph,14,04:39:26,00:19:58,00:47:53,00:03:25,00:02:20
2019/04/06,Billy Bob,Joe Joseph,11,06:33:13,00:35:45,00:17:21,00:01:35,00:04:30
2019/04/07,Billy Bob,Joe Joseph,13,05:47:06,00:26:42,00:02:03,00:00:09,00:02:27
2019/04/08,Billy Bob,Joe Joseph,11,03:20:21,00:18:13,00:00:03,00:00:00,00:02:44

Body:
This is easier then you expect, since what you have for input is XML. Try this:

$importPath = 'C:\Example.txt'
[xml]$DataIn=Get-Content $importPath
$DataIn.Envelope.Body.getReportResultCsvResponse.return| Out-File -FilePath 'C:\ResponseOnly.txt'

That will just get you what you're looking for.

If you really want to use RegEx, I would read the whole file in as a multiline string, and match against that to get your output. You just need to tell the RegEx that you're going against a multiline string when you do it.

$pattern = "(?ms)<return>(.*?)</return>"
$string = Get-Content $importPath -raw
$result = [regex]::match($string, $pattern).Groups[1].Value
$result | Out-File -FilePath 'C:\ResponseOnly.txt'