问:
How to extract original prices using BeautifulSoup?
I am trying to learn BeatifulSoup but currently having trouble with extracting prices (especially if there's a discount / strike through). I am only interested when there's a discount (itemprop = "offers") and for this exercise, I just want to extract the original price.

Full HTML can be obtain by inspecting this page:
https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests

Highlighted desired target in the HTML below:

I have tried

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd
import json

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []

for section_tag in soup.find_all('div', class_='product-tile__meta-primary'):
    for div_prices in section_tag.find_all('div', class_='price'):
        if div_prices.get('itemprop') == 'offers':
            for x in div_prices.find_all('span', {'class':'strike-through list'}):
                for y in x.find_all('span', class_='value'):
                    div_price.append(y.get('content'))
        else:
            continue
</code>```

The above code gives me the desired prices - I only want the original price ($499) and not the discounted price ($349.30) - however it gets repeated multiple times :(

['499.00',  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',
  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',
  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',  '879.00',
  '999.00', . . .

Also I'm not proud with the nested loops I'm hoping the community can help to fix these two bugs (feels like I'm missing something simple here but I just can't get my head around it):

If there's a better way without using all the loops I'm all ears

Is there a better way to extract the required info other than keep using find_all (still within BeautifulSoup)?

答:
```<code>for price in soup.select('.price'):

    if price.select('.strike-through.list'):
        print(price.select('.strike-through.list'))
    else:
        print(price.select('.sales'))
</code>```

This code should get you the price of strike-through list class if it is available, else it will get the original 'sales' class rate.

The span logic should work based on your code.

Hope this helps.

Body:
I am trying to learn BeatifulSoup but currently having trouble with extracting prices (especially if there's a discount / strike through). I am only interested when there's a discount (itemprop = "offers") and for this exercise, I just want to extract the original price.

Full HTML can be obtain by inspecting this page:
https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests

Highlighted desired target in the HTML below:

I have tried

from bs4 import BeautifulSoup
import requests
import pandas as pd
import json

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []

for section_tag in soup.find_all('div', class_='product-tile__meta-primary'):
    for div_prices in section_tag.find_all('div', class_='price'):
        if div_prices.get('itemprop') == 'offers':
            for x in div_prices.find_all('span', {'class':'strike-through list'}):
                for y in x.find_all('span', class_='value'):
                    div_price.append(y.get('content'))
        else:
            continue

The above code gives me the desired prices - I only want the original price ($499) and not the discounted price ($349.30) - however it gets repeated multiple times :(

['499.00',  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',
  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',
  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',  '879.00',
  '999.00', . . .

Also I'm not proud with the nested loops I'm hoping the community can help to fix these two bugs (feels like I'm missing something simple here but I just can't get my head around it):

If there's a better way without using all the loops I'm all ears

Is there a better way to extract the required info other than keep using find_all (still within BeautifulSoup)?

Body:
for price in soup.select('.price'):

    if price.select('.strike-through.list'):
        print(price.select('.strike-through.list'))
    else:
        print(price.select('.sales'))

This code should get you the price of strike-through list class if it is available, else it will get the original 'sales' class rate.

The span logic should work based on your code.

Hope this helps.


来源: stackexchange

问:
ResourcePurchaseValidationFailed error while creating Azure pipeline
I am getting below error while spinning up vm through Azure devops CD

Failure sending request: StatusCode=400 -- Original Error: Code="ResourcePurchaseValidationFailed" Message="User failed validation to purchase resources. Error message: 'Legal terms have not been accepted for this item on this subscription

答: It turn out to be enabling the programatic access. once its enabled make sure you are in right subscription unless its quota restricted...Azure portal </p>

ContentLicense: CC BY-SA 4.0


问:
Text data in Haskell
I am really confused with this Text data in Haskell. Can someone explain me what values it has, where can it be used and what actually is the difference between it and a normal String. Thank you in advance. </p>

答:
Text Contiguous memory that contains UTF-16 encoded text.

String A linked list of individual characters (inefficient, but having a list makes quick-and-dirty parsers easy to write)

Lazy Text from Data.Text.Lazy is a linked list of chunks of Text allowing streaming of text in constant memory.

Title: Text data in Haskell


答:
You can find the price directly by the attr itemprop on the targeted span.
For the jacket where there are 2 prices, I use find method so it take only the first found span, so the price without discount

You can do something like this:

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd
import json

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests")
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []
# Loop on elements
for jacket in soup.find_all('div', {'class':'product-tile__content'}):
    span_price = jacket.find('span', {'itemprop': 'price'})
    if span_price:
        div_price.append(span_price.get('content'))
print(div_price)
</code>```

RESULTS:

```<code>['189', '189', '189', '189', '189', '189', '189', '189', '189', '189', '435', '499.00', '435.00', '189', '879.00', '249', '499', '999.00', '799.00', '249', '749', '499', '159', '879', '685', '499', '315', '625', '169', '625', '475', '435', '599', '375', '315', '625', '499', '315']
</code>```

Title: How to extract original prices using BeautifulSoup?

Body:
You can find the price directly by the attr itemprop on the targeted span.
For the jacket where there are 2 prices, I use find method so it take only the first found span, so the price without discount

You can do something like this:

from bs4 import BeautifulSoup
import requests
import pandas as pd
import json

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests")
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []
# Loop on elements
for jacket in soup.find_all('div', {'class':'product-tile__content'}):
    span_price = jacket.find('span', {'itemprop': 'price'})
    if span_price:
        div_price.append(span_price.get('content'))
print(div_price)

RESULTS:

['189', '189', '189', '189', '189', '189', '189', '189', '189', '189', '435', '499.00', '435.00', '189', '879.00', '249', '499', '999.00', '799.00', '249', '749', '499', '159', '879', '685', '499', '315', '625', '169', '625', '475', '435', '599', '375', '315', '625', '499', '315']


问:
Javascript apply filter to a list of objects and hide respective section divider (section divider and list elements are separate)
I used javascript to create a table, which can be filtered.

The table is divided into alphabetical sections represented visually by a divider.

Once I filter the table, the divider does not disappear as it has a different class name than the list element itself.

I would not prefer to reload the entire table once the filter input changes as I think javascript should do the job too.

Here the depicted situation

```<code><div class="address_book_wrapper">
  <div class="address_top_wrapper"></div>
  <div class="address_center_wrapper">

  </div>
  <div class="contact_list_wrapper">
          <!-- search input fiels -->
      <input id="address_search_input" type="text" placeholder="Who are you looking for <?= $first_name ?>?"/>
      <div id="contact_list"></div>
    </div>
</div>
<div class="address_bottom_wrapper"></div>

</div>
</code>```

//global variables
var initial_char = null;
var address_table_container = document.getElementById('contact_list');

function process_address_data(address_data) {

  function createAddressRow(rowAddressData) {
    var name = rowAddressData[1];
    var first_char = name.charAt(0);

    if (first_char != initial_char) {
      //create new section divider
      var table_section_wrap = document.createElement("div");
      // add a class name
      table_section_wrap.className = 'rowSectionAddress';
      // letter holder
      var first_letter = document.createElement("span");
      first_letter.innerHTML = first_char;
      first_letter.className = 'address_name_table';
      //create new user row
      var table_data_wrap = document.createElement("div");
      table_data_wrap.className = 'rowDataAddress';
      //first name as well
      var address_name = document.createElement("span");
      address_name.innerHTML = rowAddressData[1] + " " + rowAddressData[2];
      address_name.className = 'address_name_table';
      //append section divider
      table_section_wrap.appendChild(first_letter);
      table_data_wrap.appendChild(address_name);
      address_table_container.appendChild(table_section_wrap);
      address_table_container.appendChild(table_data_wrap);

      //update initial_char and set to current char
      initial_char = first_char;
    } else {
      //create new user row
      var table_data_wrap = document.createElement("div");
      table_data_wrap.className = 'rowDataAddress';
      // name holder
      var address_name = document.createElement("span");
      address_name.innerHTML = rowAddressData[1] + " " + rowAddressData[2];
      address_name.className = 'address_name_table';
      //append name
      table_data_wrap.appendChild(address_name);
      address_table_container.appendChild(table_data_wrap);
    }
  }

    // loop through the data and call createRow function
  for (var i = 0, len = address_data.length; i < len; i++) {
    // get each data
    var userAddressData = address_data[i];
    // create the row (see above function)
    createAddressRow(userAddressData);
  }
}

//filter list
//todo: if filter then delete section letters
function filterContactList() {
  var input, filter, li, i, txtValue;
  input = document.getElementById("address_search_input");
  filter = input.value.toUpperCase();
  li = document.getElementsByClassName("rowDataAddress");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
```

The current result looks like this and I want to get rid of the dividers.  The other entries are hidden due to the filter

I hope this displays my problem properly.

答:
The way you code is really laborious ..

to simplify the code I used a dataset to keep the first letter directly on the element to show or hide.
I also added a noDisplaySub class. for the search / display job

https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset

const DomParser = new DOMParser()
  ,   ctx_List  = document.getElementById('contact_list')
  ,   inSearch  = document.getElementById('address_search_input')
  ;
function createSection(firstChar)
  {
  let section=
   `

       ${firstChar}

`;
  return DomParser.parseFromString( section, 'text/html').body.firstChild ;
  }
function createRows(arrData)
  {
  let row =
   `

        ${arrData[1]} ${arrData[2]}

`;
  return DomParser.parseFromString( row, 'text/html').body.firstChild ;
  }
function process_address_data(address_data)
  {
  let initial_char = null
    , ref_section  = null
    ;
  for (let address of address_data)
    {
    let first_char = address[1].charAt(0).toUpperCase()

    if (initial_char != first_char)
      {
      initial_char = first_char
      ref_section  = createSection(first_char)
      ctx_List.appendChild(ref_section)
      }

    ref_section.appendChild( createRows(address) )
    }
  }
var inSearch_key = '*'   // current address_search_input value
  ;
inSearch.oninput=e=>
  {
  let SearchLetter = inSearch.value.toUpperCase();

  SearchLetter = (SearchLetter.length > 0) ? SearchLetter.charAt(0) : '*'

  if (inSearch_key!== SearchLetter )
    {
    inSearch_key = SearchLetter
    ctx_List.querySelectorAll('.rowSectionAddress').forEach(section=>
      {
      if (inSearch_key===section.dataset.char1
      || inSearch_key==='*' )
        { section.classList.remove('noDisplaySub') }
      else
        { section.classList.add('noDisplaySub')    }
  }) } }

// --------------- test part --------------------------
const address_data
        = [ [ '', 'abc 1', 'abc 2' ]
          , [ '', 'bcd x', 'bcd y' ]
          , [ '', 'bcd w', 'bcd z' ]
          , [ '', 'ecd m', 'ecd n' ]
          , [ '', 'ecd v', 'ecd n' ]
          , [ '', 'ecd w', 'ecd n' ]
          ]

process_address_data(address_data)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.noDisplaySub > div { display: none; }</code>```

    <input id="address_search_input" type="text" placeholder="type '*' for All (or a,b,e) "/>

```

Body:
I used javascript to create a table, which can be filtered.

The table is divided into alphabetical sections represented visually by a divider.

Once I filter the table, the divider does not disappear as it has a different class name than the list element itself.

I would not prefer to reload the entire table once the filter input changes as I think javascript should do the job too.

Here the depicted situation

      <input id="address_search_input" type="text" placeholder="Who are you looking for <?= $first_name ?>?"/>

//global variables
var initial_char = null;
var address_table_container = document.getElementById('contact_list');

function process_address_data(address_data) {

  function createAddressRow(rowAddressData) {
    var name = rowAddressData[1];
    var first_char = name.charAt(0);

    if (first_char != initial_char) {
      //create new section divider
      var table_section_wrap = document.createElement("div");
      // add a class name
      table_section_wrap.className = 'rowSectionAddress';
      // letter holder
      var first_letter = document.createElement("span");
      first_letter.innerHTML = first_char;
      first_letter.className = 'address_name_table';
      //create new user row
      var table_data_wrap = document.createElement("div");
      table_data_wrap.className = 'rowDataAddress';
      //first name as well
      var address_name = document.createElement("span");
      address_name.innerHTML = rowAddressData[1] + " " + rowAddressData[2];
      address_name.className = 'address_name_table';
      //append section divider
      table_section_wrap.appendChild(first_letter);
      table_data_wrap.appendChild(address_name);
      address_table_container.appendChild(table_section_wrap);
      address_table_container.appendChild(table_data_wrap);

      //update initial_char and set to current char
      initial_char = first_char;
    } else {
      //create new user row
      var table_data_wrap = document.createElement("div");
      table_data_wrap.className = 'rowDataAddress';
      // name holder
      var address_name = document.createElement("span");
      address_name.innerHTML = rowAddressData[1] + " " + rowAddressData[2];
      address_name.className = 'address_name_table';
      //append name
      table_data_wrap.appendChild(address_name);
      address_table_container.appendChild(table_data_wrap);
    }
  }

    // loop through the data and call createRow function
  for (var i = 0, len = address_data.length; i < len; i++) {
    // get each data
    var userAddressData = address_data[i];
    // create the row (see above function)
    createAddressRow(userAddressData);
  }
}

//filter list
//todo: if filter then delete section letters
function filterContactList() {
  var input, filter, li, i, txtValue;
  input = document.getElementById("address_search_input");
  filter = input.value.toUpperCase();
  li = document.getElementsByClassName("rowDataAddress");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

The current result looks like this and I want to get rid of the dividers.  The other entries are hidden due to the filter

I hope this displays my problem properly.

Body:
The way you code is really laborious ..

to simplify the code I used a dataset to keep the first letter directly on the element to show or hide.
I also added a noDisplaySub class. for the search / display job

https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset

const DomParser = new DOMParser()
  ,   ctx_List  = document.getElementById('contact_list')
  ,   inSearch  = document.getElementById('address_search_input')
  ;
function createSection(firstChar)
  {
  let section=
   `<div class="rowSectionAddress" data-char1="${firstChar}">
       <span class="address_name_table">${firstChar}</span>
    </div>`;
  return DomParser.parseFromString( section, 'text/html').body.firstChild ;
  }
function createRows(arrData)
  {
  let row =
   `<div class="rowDataAddress">
        <span class="address_name_table">${arrData[1]} ${arrData[2]}</span>
    </div>`;
  return DomParser.parseFromString( row, 'text/html').body.firstChild ;
  }
function process_address_data(address_data)
  {
  let initial_char = null
    , ref_section  = null
    ;
  for (let address of address_data)
    {
    let first_char = address[1].charAt(0).toUpperCase()

    if (initial_char != first_char)
      {
      initial_char = first_char
      ref_section  = createSection(first_char)
      ctx_List.appendChild(ref_section)
      }

    ref_section.appendChild( createRows(address) )
    }
  }
var inSearch_key = '*'   // current address_search_input value
  ;
inSearch.oninput=e=>
  {
  let SearchLetter = inSearch.value.toUpperCase();

  SearchLetter = (SearchLetter.length > 0) ? SearchLetter.charAt(0) : '*'

  if (inSearch_key!== SearchLetter )
    {
    inSearch_key = SearchLetter
    ctx_List.querySelectorAll('.rowSectionAddress').forEach(section=>
      {
      if (inSearch_key===section.dataset.char1
      || inSearch_key==='*' )
        { section.classList.remove('noDisplaySub') }
      else
        { section.classList.add('noDisplaySub')    }
  }) } }

// --------------- test part --------------------------
const address_data
        = [ [ '', 'abc 1', 'abc 2' ]
          , [ '', 'bcd x', 'bcd y' ]
          , [ '', 'bcd w', 'bcd z' ]
          , [ '', 'ecd m', 'ecd n' ]
          , [ '', 'ecd v', 'ecd n' ]
          , [ '', 'ecd w', 'ecd n' ]
          ]

process_address_data(address_data)

.noDisplaySub > div { display: none; }

<div class="address_book_wrapper">
  <div class="address_top_wrapper"></div>
  <div class="address_center_wrapper">

  </div>
  <div class="contact_list_wrapper">
            <!-- search input fiels -->
    <input id="address_search_input" type="text" placeholder="type '*' for All (or a,b,e) "/>
    <div id="contact_list"></div>
  </div>
<div class="address_bottom_wrapper"></div>

</div>


问:
How to configure Azure AAD in API Management and call API Management endpoints from web/console app in .NET
I have gone through few articles like below

https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad

but It didnt worked.

I'm getting error as AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '24gktm5-5khpnj3h9nphkmm=h-hh2h58h9'.

I have followed everything as mentioned but not getting where I did wrong.

Also can someone share code to call APIM endpoints from console app.

答:
The redirect URIs for your AD app (Application ID : 24gktm5-5khpnj3h9nphkmm=h-hh2h58h9) needs to include the URI from the OAuth configuration under APIM.

From the OAuth settings of APIM, under where you enter the client secret you should see "This is what the redirect_uri for authorization code grant type looks like", copy this URL into the redirect URIs for your AD app registration.


问:
Serial communication in Java
I have problem with Serialio library for using serial port, it works on XP but it doesn't work on Windows 7 on my computer, but what is strange works on Windows 7 on friend computer. I got message, not error, Platform not supported. Does anybody have any experience with this ?</p>

答:
check settings of serial I/O? I am not familiar with serialIO library but I know some serial Win32 APIs.
I read some sample code like this:

```<code>GetCommState(hport, &mDCB);
/* do something to change settings */
SetCommState(hport, &mDCB);
</code>```

In some situation, this would cause unexpected problem.
Retrieved variables are not all modified by your program and those un-modified part might change the result of execution.

ContentLicense: CC BY-SA 3.0

Title: Serial communication in Java

Body:
check settings of serial I/O? I am not familiar with serialIO library but I know some serial Win32 APIs.
I read some sample code like this:

GetCommState(hport, &mDCB);
/* do something to change settings */
SetCommState(hport, &mDCB);

In some situation, this would cause unexpected problem.
Retrieved variables are not all modified by your program and those un-modified part might change the result of execution.


问:
Required request body is missing in Spring when Angular Post call is sent
In my Angular application I'm trying to create a POST request, with a json body, that will be sent to my Spring Restful back-end; I have created a service in Angular to handle the API Post method but when I try to send the request, I obtain this error in my front-end console:

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8080/center/search_1/page/0", ok: false, …}

and this error in my back-end console:

Required request body is missing: public org.springframework.data.domain.Page

This is the code of my service in Angular:

```<code>import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: JSON): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, JSON.stringify(body),
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}
</code>```

and this is a part of the code of a component that triggers the API call:

```<code>funcThis.apiCenterSearch1Service.getFirstQuery(JSON.parse(jsonRequest)).subscribe(
              res => {
                console.log(res);
              });
</code>```

I've already tested my Spring API through Insomnia (an API tester application) and it works without any problems (and I also checked that the JSON required by the back-end is well formatted so I don't think that the problem is this).

Where am I doing wrong?

答:
Please try below code

```<code>import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: any): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, body,
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}
</code>```

And your service code should be like

```<code>this.apiCenterSearch1Service.getFirstQuery(jsonRequest).subscribe(
          res => {
            console.log(res);
          });
</code>```

Body:
In my Angular application I'm trying to create a POST request, with a json body, that will be sent to my Spring Restful back-end; I have created a service in Angular to handle the API Post method but when I try to send the request, I obtain this error in my front-end console:

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8080/center/search_1/page/0", ok: false, …}

and this error in my back-end console:

Required request body is missing: public org.springframework.data.domain.Page

This is the code of my service in Angular:

import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: JSON): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, JSON.stringify(body),
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}

and this is a part of the code of a component that triggers the API call:

funcThis.apiCenterSearch1Service.getFirstQuery(JSON.parse(jsonRequest)).subscribe(
              res => {
                console.log(res);
              });

I've already tested my Spring API through Insomnia (an API tester application) and it works without any problems (and I also checked that the JSON required by the back-end is well formatted so I don't think that the problem is this).

Where am I doing wrong?

Body:
Please try below code

import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: any): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, body,
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}

And your service code should be like

this.apiCenterSearch1Service.getFirstQuery(jsonRequest).subscribe(
          res => {
            console.log(res);
          });


问:
Add plugins (Vue.use) after instance mounting (new Vue().$mount())
I have some vue plugins, like analytics, sentry etc. which require  configuration data from server to set up.

I have to make a request for configuration, next do a Vue.use() and in the end, call new Vue() instance. I think it can make some performance effort because Vue.$mount creates a lot of DOM elements and runs javascript logic and it happens after XHR request/response. So my question is: what is the best solution, patterns to solve described problem?

Can I avoid fetching configuration data (maybe put data in some static file by webpack during build process (data are stored in MySQL)
Or maybe can I use Vue.use after creating Vue instance?

答:
I prefer avoid fetching configuration data in server. In my opition you must put the configuration in static file for building with webpack.

But I will answer your question: the Vue don't have restrictions about to load plugins after Vue instance created. It's work.

See the bellow example.

```<code><template>
  <div>
    <button type="button" @click="installPlugin">install plugin</button>
    <button type="button" @click="callPlugin">call plugin</button>
  </div>
</template>

<script>
import Vue from 'vue';

export default {
  name: 'app',
  methods: {
    installPlugin() {
      Vue.use({
        install(Vue, options) {
          console.log('plugin was installed');

          Vue.prototype.$test = () => {
            console.log('plugin was called');
            return 'run-test';
          };
        },
      });
    },
    callPlugin() {
      this.$test();
    },
  },
};
</script>
</code>```

In this example, the Vue Plugin can be installed and called after Vue instance created.

Body:
I prefer avoid fetching configuration data in server. In my opition you must put the configuration in static file for building with webpack.

But I will answer your question: the Vue don't have restrictions about to load plugins after Vue instance created. It's work.

See the bellow example.

<template>
  <div>
    <button type="button" @click="installPlugin">install plugin</button>
    <button type="button" @click="callPlugin">call plugin</button>
  </div>
</template>

<script>
import Vue from 'vue';

export default {
  name: 'app',
  methods: {
    installPlugin() {
      Vue.use({
        install(Vue, options) {
          console.log('plugin was installed');

          Vue.prototype.$test = () => {
            console.log('plugin was called');
            return 'run-test';
          };
        },
      });
    },
    callPlugin() {
      this.$test();
    },
  },
};
</script>

In this example, the Vue Plugin can be installed and called after Vue instance created.


问:
WCF decoupling via ViewModel facade ASP.NET
I am consuming several ASP.NET 4, WCF services in C# and want to know the best way of decoupling my code from the WCF structure. If this is not too much work as the client probably doesn't care.

I created a facade layer so my WebForms UI can talk to it using flat simple types like string, int and datetime. The facade generates and read the Request/Response objects required by the WCF. I read the Response object and convert it into a simpler Presentation object for the client to use. However the Response object returns some complex object types, such as OrderHistory which contains OrderItem, which in itself contains for e.g. DeliveryAddress.

Now should I be recreating all these complex objects as Views? i.e. OrderPresentation contains IEnumerable-OrderHistoryView-, which contains IEnumerable-OrderItemView-, which contains DeliveryAddressView or am I misinterpreting this?

For some of the simpler objects I have been able to use AutoMapper but not sure how or if I should apply it to nested complex objects. Maybe I should not bother decoupling so much and just bind my facade and presentation objects to the WCF model?

Help please? any good tutorial examples on this?

I'm getting somewhere with:

```<code>        public static IList<OrderHistoryView> ConvertToOrderHistoryView(this OrderHistory[] orderHistory)
    {
        return Mapper.Map<OrderHistory[], IList<OrderHistoryView>>(orderHistory);
    }
</code>```

and

```<code>            Mapper.CreateMap<OrderHistory, OrderHistoryView>()
            .ForMember(dest => dest.Items, opt => opt.MapFrom(src => src.Items));
</code>```

答:
If you write some DTO classes to dump the data from WCF into, then you should be able to use AutoMapper to handle the mapping. I'm not really sure why, though. Is there any realistic scenario where you'd ever be able to take this app, connect it to a different service, and NOT have to make significant changes to the client code?

If the answer is no and your client is pretty well dependent on the services in question, then you're just wasting energy worrying about it. I guarantee that your users don't care.

Body:
I am consuming several ASP.NET 4, WCF services in C# and want to know the best way of decoupling my code from the WCF structure. If this is not too much work as the client probably doesn't care.

I created a facade layer so my WebForms UI can talk to it using flat simple types like string, int and datetime. The facade generates and read the Request/Response objects required by the WCF. I read the Response object and convert it into a simpler Presentation object for the client to use. However the Response object returns some complex object types, such as OrderHistory which contains OrderItem, which in itself contains for e.g. DeliveryAddress.

Now should I be recreating all these complex objects as Views? i.e. OrderPresentation contains IEnumerable-OrderHistoryView-, which contains IEnumerable-OrderItemView-, which contains DeliveryAddressView or am I misinterpreting this?

For some of the simpler objects I have been able to use AutoMapper but not sure how or if I should apply it to nested complex objects. Maybe I should not bother decoupling so much and just bind my facade and presentation objects to the WCF model?

Help please? any good tutorial examples on this?

I'm getting somewhere with:

        public static IList<OrderHistoryView> ConvertToOrderHistoryView(this OrderHistory[] orderHistory)
    {
        return Mapper.Map<OrderHistory[], IList<OrderHistoryView>>(orderHistory);
    }

and

            Mapper.CreateMap<OrderHistory, OrderHistoryView>()
            .ForMember(dest => dest.Items, opt => opt.MapFrom(src => src.Items));


问:
SQL Query between two dates from sub query
I have to filter my result by two columns from sub query,so I have join them like below which works fine.

```<code>select * from EDM_STATUS_REPORT_DATA LEFT JOIN
(
   Select DocumentID, LogDate
   From [LM_StateEvents]
   Where 1=1

) table2
ON
   EDM_STATUS_REPORT_DATA.LLObjID=table2.DocumentID
   AND EDM_STATUS_REPORT_DATA.StatusDate = table2.LogDate
WHERE table2.DocumentID IS NOT NULL
</code>```

However the EDM_STATUS_REPORT_DATA.StatusDate in main query is not going to be the same value from sub query.It would have maximum of +5 seconds difference.  So I have to search like using between table2.LogDate and table2.LogDate + 5 seconds.

How can I achieve this.

Below is the sample data and Expected output.

答:
You can greatly simplify this by joining to the table instead of making a subquery and joining to that. Also, you should use an inner join instead of a left join because your where predicate is changing it into an inner join. I don't condone using functions like this in your join predicates because they are nonSARGable. You should probably fix the design so you don't have to do this. But given the current tables as you have them you can do something like this.</p>

```<code>select *
from EDM_STATUS_REPORT_DATA  rd
JOIN LM_StateEvents se on rd.LLObjID = se.DocumentID
   AND abs(datediff(second, rd.StatusDate = se.LogDate)) <= 5
</code>```

Body:
I have to filter my result by two columns from sub query,so I have join them like below which works fine.

select * from EDM_STATUS_REPORT_DATA LEFT JOIN
(
   Select DocumentID, LogDate
   From [LM_StateEvents]
   Where 1=1

) table2
ON
   EDM_STATUS_REPORT_DATA.LLObjID=table2.DocumentID
   AND EDM_STATUS_REPORT_DATA.StatusDate = table2.LogDate
WHERE table2.DocumentID IS NOT NULL

However the EDM_STATUS_REPORT_DATA.StatusDate in main query is not going to be the same value from sub query.It would have maximum of +5 seconds difference.  So I have to search like using between table2.LogDate and table2.LogDate + 5 seconds.

How can I achieve this.

Below is the sample data and Expected output.

Body:
You can greatly simplify this by joining to the table instead of making a subquery and joining to that. Also, you should use an inner join instead of a left join because your where predicate is changing it into an inner join. I don't condone using functions like this in your join predicates because they are nonSARGable. You should probably fix the design so you don't have to do this. But given the current tables as you have them you can do something like this.

select *
from EDM_STATUS_REPORT_DATA  rd
JOIN LM_StateEvents se on rd.LLObjID = se.DocumentID
   AND abs(datediff(second, rd.StatusDate = se.LogDate)) <= 5


问:
How to display two images on two UIImageViews one View Controller, UIImagePickerController's?
I want to pick images from phone library when I tap on two different UIImageViews and after selection, display them on two different UIImageView's,
but I when run the following code, the same image displays at two different UIImageViews, How can I fix it?
'''</p>

```<code>extension SettingProfileViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
           profilePhoto.image = image
            print("profile")
        }

        if let wallImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            wallpaperPhoto.image = wallImage
            print("wallpaper")
        }

        dismiss(animated: true, completion: nil)

    }

}
override func viewDidLoad() {
        super.viewDidLoad()
     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelectProfilePhotoView))
        profilePhoto.addGestureRecognizer(tapGesture)
        profilePhoto.isUserInteractionEnabled = true

     let wallTapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelectWallpaperImageView))
        wallpaperPhoto.addGestureRecognizer(wallTapGesture)
        wallpaperPhoto.isUserInteractionEnabled = true
}

 @objc func handleSelectProfilePhotoView(){
        let pickerController = UIImagePickerController() //открывает галерею
        pickerController.delegate = self
        present(pickerController, animated: true, completion: nil)
    }

    @objc func handleSelectWallpaperImageView(){
        let pickerCont = UIImagePickerController()
        pickerCont.delegate = self
        present(pickerCont, animated: true, completion: nil)
    }

'''
</code>```

答:
What you observe is that when the user taps on any of the image views (wallpaperPhoto or profilePhoto), the UIImagePickerController always uses self as its delegate. Then, when the user picks an image, the delegate cannot distinguish any more which image view originally was tapped.

You could simply add a weak optional variable indicating the "active" tapped image view, and then set only it's image. Also, you can reduce the tap handler to a single function with a sender argument, which is the image view the user tapped on, and set the activeImageViewto this.

```<code>extension SettingProfileViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    weak var activeImageView:UIImageView? = nil

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
           activeImageView.image = image
        }
        dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
         super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelect(_:))
            profilePhoto.addGestureRecognizer(tapGesture)
            profilePhoto.isUserInteractionEnabled = true

         let wallTapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelect(_:)))
            wallpaperPhoto.addGestureRecognizer(wallTapGesture)
            wallpaperPhoto.isUserInteractionEnabled = true
    }

    @objc func handleSelect(sender:UIGestureRecognizer) {
        guard let sendingImageView = sender.view as? UIImageView else {
            print("Ooops, received this gesture not from an ImageView")
            return
        }
        activeImageView = sendingImageView
        let pickerController = UIImagePickerController() //открывает галерею
        pickerController.delegate = self
        present(pickerController, animated: true, completion: nil)
    }

// ...
</code>```

Body:
I want to pick images from phone library when I tap on two different UIImageViews and after selection, display them on two different UIImageView's,
but I when run the following code, the same image displays at two different UIImageViews, How can I fix it?
'''

extension SettingProfileViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
           profilePhoto.image = image
            print("profile")
        }

        if let wallImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            wallpaperPhoto.image = wallImage
            print("wallpaper")
        }

        dismiss(animated: true, completion: nil)

    }

}
override func viewDidLoad() {
        super.viewDidLoad()
     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelectProfilePhotoView))
        profilePhoto.addGestureRecognizer(tapGesture)
        profilePhoto.isUserInteractionEnabled = true

     let wallTapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelectWallpaperImageView))
        wallpaperPhoto.addGestureRecognizer(wallTapGesture)
        wallpaperPhoto.isUserInteractionEnabled = true
}

 @objc func handleSelectProfilePhotoView(){
        let pickerController = UIImagePickerController() //открывает галерею
        pickerController.delegate = self
        present(pickerController, animated: true, completion: nil)
    }

    @objc func handleSelectWallpaperImageView(){
        let pickerCont = UIImagePickerController()
        pickerCont.delegate = self
        present(pickerCont, animated: true, completion: nil)
    }

'''

Body:
What you observe is that when the user taps on any of the image views (wallpaperPhoto or profilePhoto), the UIImagePickerController always uses self as its delegate. Then, when the user picks an image, the delegate cannot distinguish any more which image view originally was tapped.

You could simply add a weak optional variable indicating the "active" tapped image view, and then set only it's image. Also, you can reduce the tap handler to a single function with a sender argument, which is the image view the user tapped on, and set the activeImageViewto this.

extension SettingProfileViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    weak var activeImageView:UIImageView? = nil

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
           activeImageView.image = image
        }
        dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
         super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelect(_:))
            profilePhoto.addGestureRecognizer(tapGesture)
            profilePhoto.isUserInteractionEnabled = true

         let wallTapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelect(_:)))
            wallpaperPhoto.addGestureRecognizer(wallTapGesture)
            wallpaperPhoto.isUserInteractionEnabled = true
    }

    @objc func handleSelect(sender:UIGestureRecognizer) {
        guard let sendingImageView = sender.view as? UIImageView else {
            print("Ooops, received this gesture not from an ImageView")
            return
        }
        activeImageView = sendingImageView
        let pickerController = UIImagePickerController() //открывает галерею
        pickerController.delegate = self
        present(pickerController, animated: true, completion: nil)
    }

// ...


问:
Replicate STUFF in Snowflake SQL
Hello Snowflake Community,

I am attempting to replicate the STUFF function in Snowflake. I didn't find a like-named function on the reference list and so was hoping someone could point me in the right direction?

Googled example

Thank you good folks

DU

答:
You can construct a string.  So, for:

```<code>stuff(col, x, y, str)
</code>```

Use:

```<code>left(col, x) || str || substr(col, x + y + 1)
</code>```

Title: Replicate STUFF in Snowflake SQL

Body:
You can construct a string.  So, for:

stuff(col, x, y, str)

Use:

left(col, x) || str || substr(col, x + y + 1)


问:
Using observable with sort data alphabetical
i am using angular 8 with asp.net core so i want to display the customer's name in the dropdown list  as alphabetical order from the api service, i found out the only solution to use the observable. is there other way to implement that? and how i can use alphabetical sort in the observable?

```<code>getAllcustomer() {
    return this._http.get<any>(this.myAppUrl + '/api/users/getcustomer', {responseType: 'json'} )
      .catch(this.errorHandler);
}
</code>```

Thanks

答:
Observables, Simply put, are a stream of data, we use observales with API calls (in your case asp.net ).

what you are trying to sort is the data (response) that came from the API, not the observable itself. You have two options here, either you sort using pipes (Rxjs operators) in the service itself or you sort a regular JS array in the component (where you subscribe to the observale).

in the service

```<code>getAllcustomer() {
    return this._http.get<any>(
                    this.myAppUrl + '/api/users/getcustomer',
                    {responseType: 'json'})
            .pipe(
                map(res => res.sort((a,b) => a.name - b.name);),
                catchError(this.errorHandler()) // use catch inside the pipe
            );
}
</code>```

or in the compnent

```<code>this._customerService.getAllcustomer().subscribe(data => {
     const sortedData = data.sort((a,b) => a.name - b.name);
})
</code>```

Body:
i am using angular 8 with asp.net core so i want to display the customer's name in the dropdown list  as alphabetical order from the api service, i found out the only solution to use the observable. is there other way to implement that? and how i can use alphabetical sort in the observable?

getAllcustomer() {
    return this._http.get<any>(this.myAppUrl + '/api/users/getcustomer', {responseType: 'json'} )
      .catch(this.errorHandler);
}

Thanks

Body:
Observables, Simply put, are a stream of data, we use observales with API calls (in your case asp.net ).

what you are trying to sort is the data (response) that came from the API, not the observable itself. You have two options here, either you sort using pipes (Rxjs operators) in the service itself or you sort a regular JS array in the component (where you subscribe to the observale).

in the service

getAllcustomer() {
    return this._http.get<any>(
                    this.myAppUrl + '/api/users/getcustomer',
                    {responseType: 'json'})
            .pipe(
                map(res => res.sort((a,b) => a.name - b.name);),
                catchError(this.errorHandler()) // use catch inside the pipe
            );
}

or in the compnent

this._customerService.getAllcustomer().subscribe(data => {
     const sortedData = data.sort((a,b) => a.name - b.name);
})


问:
Unable to get the handle of a newly opened window in IE using java
I am clicking on a button in my code "Go" which opens a new window.
When I check the task manager I can see the instances of IE as 2 but getWindowHandles() is unable to get the handle of the newly opened window and just returns the parent window handle.

The code that I am using to do this is:

SeleniumUtils.clickOnElement(webDriver, By.xpath("//input[@name='Go' and @value='Go']"), "Click on Go", reporter);
SeleniumUtils.waitLoading(SeleniumUtils.WAIT_LONG);

List<String> windowsList = new ArrayList<>();
String parentWindow = webDriver.getWindowHandle();
windowsList.add(parentWindow);

String emailWindow = SeleniumUtils.changeDriverToTheNewWindow(webDriver, windowsList, windowsList.size()+1);
windowsList.add(emailWindow);
```

<p>To change to the new window, I have written a function:</p>

<pre class="lang-java prettyprint-override"><code>public static String changeDriverToTheNewWindow(WebDriver webDriver, List<String> previousWindows, int numberOfWindows) {
    try {
        JavascriptExecutor jsExecuter = (JavascriptExecutor) webDriver;
        Set<String> windows = Collections.emptySet();
        try
        {
            WebDriverWait wait = new WebDriverWait (webDriver, 5);
            wait.until(ExpectedConditions.numberOfWindowsToBe(numberOfWindows));
            windows = webDriver.getWindowHandles();
        }catch(Exception e) {
            lLogger.error("Error getting the window handles.", e);
            windows = webDriver.getWindowHandles();
        }

        for (String windowId : windows) {
            if (!previousWindows.contains(windowId)) {
                webDriver.switchTo().window(windowId);
                jsExecuter.executeScript("window.focus");
                //changeDriverToWindow(webDriver, windowId);
                return windowId;
            }
        }
    } catch (Exception e) {
        lLogger.error("Error changing driver to the new window!", e);
    }
    return null;
}
</code>```

The HTML & JS code that opens the window is:

```<code><td class="xyz-column">

<link href="../Content/css/XYZ.css" rel="stylesheet" type="text/css">

<script type="text/javascript">
    function onMouseOver(control) {
        control.src = '../Content/images/lookup.png';
    }
    function onMouseOut(control) {
        control.src = '../Content/images/btn_lookup.png';
    }
</script>

<span class="xyz-link" id="body_XYZSelector_XYZLookup_LookupName" style="width: 175px; height: 18px; display: inline-block;" onclick="OpenXYZ(GetCurrentLookupId(this),'42e7a262-36ef-e911-80f1-005056aea4ce','10001'); return false;"> SHARANA </span>
<img class="xyz-lookup" id="body_XYZSelector_XYZLookup_LookupImage" onmouseover="onMouseOver(this);" onmouseout="onMouseOut(this);" onclick="OpenLookUp(this);" alt="Browse" src="../Content/images/btn_lookup.png" entitytype="xyz">

<input name="ctl00$body$XYZSelector$XYZLookup$LookupHiddenId" id="body_XYZSelector_XYZLookup_LookupHiddenId" type="hidden" value="56765">

<input name="ctl00$body$XYZSelector$XYZLookup$LookupHiddenName" id="body_XYZSelector_XYZLookup_LookupHiddenName" type="hidden" value="SHARANA">

<input name="ctl00$body$XYZSelector$XYZLookup$LookupHiddenId" id="body_XYZSelector_XYZLookup_LookupHiddenId" type="hidden" value="fd878f2b-90a2-4bf0-8a00-daa007b64b7d">

</td>
</code>```

答:
I found the solution to my problem. Just make sure you follow all the steps as you see at Solution answered by @DebanjanB.

To be more specific, in my case it was the
...
InternetExplorerOptions options = new InternetExplorerOptions();
options.merge(cap);
WebDriver driver = new InternetExplorerDriver(options);

as you can see at Solution 1 and

ieCapabilities.setCapability("requireWindowFocus", false);

as you can see at Solution 2

After adding these two, the driver was able to get the handle of the window correctly.

Body:
I am clicking on a button in my code "Go" which opens a new window.
When I check the task manager I can see the instances of IE as 2 but getWindowHandles() is unable to get the handle of the newly opened window and just returns the parent window handle.

The code that I am using to do this is:

SeleniumUtils.clickOnElement(webDriver, By.xpath("//input[@name='Go' and @value='Go']"), "Click on Go", reporter);
SeleniumUtils.waitLoading(SeleniumUtils.WAIT_LONG);

List<String> windowsList = new ArrayList<>();
String parentWindow = webDriver.getWindowHandle();
windowsList.add(parentWindow);

String emailWindow = SeleniumUtils.changeDriverToTheNewWindow(webDriver, windowsList, windowsList.size()+1);
windowsList.add(emailWindow);

To change to the new window, I have written a function:

public static String changeDriverToTheNewWindow(WebDriver webDriver, List<String> previousWindows, int numberOfWindows) {
    try {
        JavascriptExecutor jsExecuter = (JavascriptExecutor) webDriver;
        Set<String> windows = Collections.emptySet();
        try
        {
            WebDriverWait wait = new WebDriverWait (webDriver, 5);
            wait.until(ExpectedConditions.numberOfWindowsToBe(numberOfWindows));
            windows = webDriver.getWindowHandles();
        }catch(Exception e) {
            lLogger.error("Error getting the window handles.", e);
            windows = webDriver.getWindowHandles();
        }

        for (String windowId : windows) {
            if (!previousWindows.contains(windowId)) {
                webDriver.switchTo().window(windowId);
                jsExecuter.executeScript("window.focus");
                //changeDriverToWindow(webDriver, windowId);
                return windowId;
            }
        }
    } catch (Exception e) {
        lLogger.error("Error changing driver to the new window!", e);
    }
    return null;
}

The HTML & JS code that opens the window is:

<link href="../Content/css/XYZ.css" rel="stylesheet" type="text/css">

 SHARANA

<input name="ctl00$body$XYZSelector$XYZLookup$LookupHiddenId" id="body_XYZSelector_XYZLookup_LookupHiddenId" type="hidden" value="56765">

<input name="ctl00$body$XYZSelector$XYZLookup$LookupHiddenName" id="body_XYZSelector_XYZLookup_LookupHiddenName" type="hidden" value="SHARANA">

<input name="ctl00$body$XYZSelector$XYZLookup$LookupHiddenId" id="body_XYZSelector_XYZLookup_LookupHiddenId" type="hidden" value="fd878f2b-90a2-4bf0-8a00-daa007b64b7d">


问:
Making the configuration available to all classes
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.

However, the config data is required on almost every level of the server - classes within classes within classes...

My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?

答: If you're doing this in Java, I would place all the configuration in Spring and then either use the Application Context to lookup the settings or simply inject them into your beans.  Spring excels at this sort of thing.</p>


问:
Linq replace values until first X value
I have a list:

```<code>var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
</code>```

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

```<code>var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)
</code>```

Actual Result:

```<code>{null,null,null,null,null,null,null,5,6,3,0,null,null,3}
</code>```

Expected Result:

```<code>{null,null,null,null,null,null,4,5,6,3,0,0,2,3}
</code>```

MRE:

```<code>public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}
</code>```

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

答:
Here is a solution I came up with. It's not quite as elegant, but it works and uses Select:

```<code>var l = new List<int?> { 0, 0, 0, 0, 0, 0, 4, 5, 6, 3, 0, 0, 2, 3 };
var firstIndex = l.FindIndex(x => x != 0);
var m = l.Select((item, index) => firstIndex == -1 || index < firstIndex ? null : item);
</code>```

This code will also replace all elements with null, if every element is zero.

Here is an example of it working in both cases: https://dotnetfiddle.net/wJMBfx

Title: Linq replace values until first X value

Body:
I have a list:

var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)

Actual Result:

{null,null,null,null,null,null,null,5,6,3,0,null,null,3}

Expected Result:

{null,null,null,null,null,null,4,5,6,3,0,0,2,3}

MRE:

public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

Body:
Here is a solution I came up with. It's not quite as elegant, but it works and uses Select:

var l = new List<int?> { 0, 0, 0, 0, 0, 0, 4, 5, 6, 3, 0, 0, 2, 3 };
var firstIndex = l.FindIndex(x => x != 0);
var m = l.Select((item, index) => firstIndex == -1 || index < firstIndex ? null : item);

This code will also replace all elements with null, if every element is zero.

Here is an example of it working in both cases: https://dotnetfiddle.net/wJMBfx


问:
Async progress bar in WPF using binding
I have a problem with visualizing the MVVM WPF progress bar. My methods for the main script runs but the progress bar isn't updating at all. I could use tips on getting in the right direction. In my previous codes, I was given tips to use Progress<T> (by @Jonathan Willcock) but I couldn't implement it successfully.

(Please note that this post is not a repeated question because last time, I used button click but I want it to purely be run on data binding)

Question

How do I asynchronously bind the progress bar to the method which is called in my view models? I am using Delegate command to call my methods and I do not want to use the button click event.

What I have in the view - XAML

I have two main functions here, the progress bar and the button. The button starts the method calling successfully but the progress bar doesn't load.

    <ProgressBar Name="pbStatus"
                         Minimum="0"
                         Value="{Binding PrgBarVal, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
                         Maximum="100"
                         Height="20"/>
    <Button x:Name = "ApplyButton" Margin="0 1 0 1" Content ="Run software" Command="{Binding RunCalcBtn, Mode=TwoWay}"/>
```

<p><strong>What I have in the XAML.cs</strong></p>

<p>What I know from the background worker method is that it tries to run it async. I have an issue here, I added a breakpoint here to check if the code runs through the 'Window_ContentRendered' method but it doesn't.</p>

<pre class="lang-cs prettyprint-override"><code>    public partial class UserInterface: UserControl
    {
        public UserInterface()
        {
            InitializeComponent();
        }
        private void Window_ContentRendered(object sender, EventArgs e)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += worker_DoWork; //Do I need a worker.ProgressChanged here?
            worker.RunWorkerAsync();
        }
        thenamespace.ViewModel.SelectedViewModel get = new thenamespace.ViewModel.SelectedViewModel ();
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {

            for (int i = Convert.ToInt32(get.PrgBarVal); i < 100; i++)
            {
                (sender as BackgroundWorker).ReportProgress(i);
            }
        }
    }
</code>```

What I have in the View Model

In the view model, I am using delegate command to call my data binding methods.

The public SelectedViewModel() is where the Run() method is called. In the Run() method, the functions in there runs correctly and updates the value of PrgBarVal correctly. However, this doesn't update the progress bar at all.

    public class SelectedViewModel : ModelView, INotifyPropertyChanged
    {
        public ModelView modelView { get; set; }

        private DelegateCommand _runCalcBtn;
        public DelegateCommand RunCalcBtn
        {
            get { return _runCalcBtn; }
            set
            {
                _runCalcBtn = value;
                SetPropertyChanged("RunCalcBtn"); //Same as RaisedPropertyChanged
            }
        }
        public SelectedViewModel()
        {
            modelView = new ModelView();
            RunCalcBtn = new DelegateCommand(Run);
        }

        private int _prgBarVal;
        public int PrgBarVal
        {
            get { return _prgBarVal; }
            set
            {
                _prgBarVal = value;
                OnPropertyChanged("PrgBarVal"); //Same as RaisedPropertyChanged
            }
        }

        //Main Function
        private async void Run()
        {

            MethodToWork(); //Function that calls other methods to run
        }
```

Thank you very much for your help!

答:
Here is the ViewModel (used NuGet ReactiveUI.WPF)

public class MainViewModel : ReactiveObject
{
    private int _workProgress;

    public MainViewModel()
    {
        IProgress<int> progress = new Progress<int>( e => WorkProgress = e );
        StartWork = ReactiveCommand.CreateFromTask( () => ExecuteStartWorkAsync( progress ) );

    }

    private async Task ExecuteStartWorkAsync( IProgress<int> progress )
    {
        progress.Report( 0 );
        for ( int i = 0; i < 1000; i++ )
        {
            await Task.Delay( 10 ).ConfigureAwait( false );
            progress.Report( (int)Math.Floor( i / 1000.0 * 100.0 ) );
        }
    }

    public int WorkProgress { get => _workProgress; private set => this.RaiseAndSetIfChanged( ref _workProgress, value ); }
    public ICommand StartWork { get; }
}
```

<p>and the View</p>

```<Window x:Class="WpfApp4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Content="Start work" Command="{Binding StartWork}" Width="80"/>
            <ProgressBar Value="{Binding WorkProgress,Mode=OneWay}" Width="120"/>
        </StackPanel>
    </Grid>
</Window>
```

Title: Async progress bar in WPF using binding

Body:
I have a problem with visualizing the MVVM WPF progress bar. My methods for the main script runs but the progress bar isn't updating at all. I could use tips on getting in the right direction. In my previous codes, I was given tips to use Progress<T> (by @Jonathan Willcock) but I couldn't implement it successfully.

(Please note that this post is not a repeated question because last time, I used button click but I want it to purely be run on data binding)

Question

How do I asynchronously bind the progress bar to the method which is called in my view models? I am using Delegate command to call my methods and I do not want to use the button click event.

What I have in the view - XAML

I have two main functions here, the progress bar and the button. The button starts the method calling successfully but the progress bar doesn't load.

    <ProgressBar Name="pbStatus"
                         Minimum="0"
                         Value="{Binding PrgBarVal, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
                         Maximum="100"
                         Height="20"/>
    <Button x:Name = "ApplyButton" Margin="0 1 0 1" Content ="Run software" Command="{Binding RunCalcBtn, Mode=TwoWay}"/>

What I have in the XAML.cs

What I know from the background worker method is that it tries to run it async. I have an issue here, I added a breakpoint here to check if the code runs through the 'Window_ContentRendered' method but it doesn't.

    public partial class UserInterface: UserControl
    {
        public UserInterface()
        {
            InitializeComponent();
        }
        private void Window_ContentRendered(object sender, EventArgs e)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += worker_DoWork; //Do I need a worker.ProgressChanged here?
            worker.RunWorkerAsync();
        }
        thenamespace.ViewModel.SelectedViewModel get = new thenamespace.ViewModel.SelectedViewModel ();
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {

            for (int i = Convert.ToInt32(get.PrgBarVal); i < 100; i++)
            {
                (sender as BackgroundWorker).ReportProgress(i);
            }
        }
    }

What I have in the View Model

In the view model, I am using delegate command to call my data binding methods.

The public SelectedViewModel() is where the Run() method is called. In the Run() method, the functions in there runs correctly and updates the value of PrgBarVal correctly. However, this doesn't update the progress bar at all.

    public class SelectedViewModel : ModelView, INotifyPropertyChanged
    {
        public ModelView modelView { get; set; }

        private DelegateCommand _runCalcBtn;
        public DelegateCommand RunCalcBtn
        {
            get { return _runCalcBtn; }
            set
            {
                _runCalcBtn = value;
                SetPropertyChanged("RunCalcBtn"); //Same as RaisedPropertyChanged
            }
        }
        public SelectedViewModel()
        {
            modelView = new ModelView();
            RunCalcBtn = new DelegateCommand(Run);
        }

        private int _prgBarVal;
        public int PrgBarVal
        {
            get { return _prgBarVal; }
            set
            {
                _prgBarVal = value;
                OnPropertyChanged("PrgBarVal"); //Same as RaisedPropertyChanged
            }
        }

        //Main Function
        private async void Run()
        {

            MethodToWork(); //Function that calls other methods to run
        }

Thank you very much for your help!

Body:
Here is the ViewModel (used NuGet ReactiveUI.WPF)

public class MainViewModel : ReactiveObject
{
    private int _workProgress;

    public MainViewModel()
    {
        IProgress<int> progress = new Progress<int>( e => WorkProgress = e );
        StartWork = ReactiveCommand.CreateFromTask( () => ExecuteStartWorkAsync( progress ) );

    }

    private async Task ExecuteStartWorkAsync( IProgress<int> progress )
    {
        progress.Report( 0 );
        for ( int i = 0; i < 1000; i++ )
        {
            await Task.Delay( 10 ).ConfigureAwait( false );
            progress.Report( (int)Math.Floor( i / 1000.0 * 100.0 ) );
        }
    }

    public int WorkProgress { get => _workProgress; private set => this.RaiseAndSetIfChanged( ref _workProgress, value ); }
    public ICommand StartWork { get; }
}

and the View

<Window x:Class="WpfApp4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Content="Start work" Command="{Binding StartWork}" Width="80"/>
            <ProgressBar Value="{Binding WorkProgress,Mode=OneWay}" Width="120"/>
        </StackPanel>
    </Grid>
</Window>


问:
Given the quarter number and year, how to find the date ranges?
I am trying create a function that will return date ranges if I pass in the quarter number (1,2,3, or 4) and the year for that quarter.

Here is what I have so far:

```<code>export const getCurrentQuarterRangeString = (quarter, year) => {
  // let year = moment().year(year);
  let start = moment().quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  let end = moment().quarter(quarter).endOf('quarter').format('YYYY-MM-DD');
  let dateRangeString = `${start};#${end}`;
  return dateRangeString;
}
</code>```

I get tripped up on trying to figure out how to key off that year parameter for MomentJS.

答:
Instantiate the moment with a date from your desired year</p>

```<code>export const getCurrentQuarterRangeString = (quarter, year) => {
  const d = new Date();
  d.setFullYear(year);
  moment = moment(d);

  let start = moment.quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  let end = moment.quarter(quarter).endOf('quarter').format('YYYY-MM-DD');
  let dateRangeString = `${start};#${end}`;
  return dateRangeString;
}
</code>```

Body:
I am trying create a function that will return date ranges if I pass in the quarter number (1,2,3, or 4) and the year for that quarter.

Here is what I have so far:

export const getCurrentQuarterRangeString = (quarter, year) => {
  // let year = moment().year(year);
  let start = moment().quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  let end = moment().quarter(quarter).endOf('quarter').format('YYYY-MM-DD');
  let dateRangeString = `${start};#${end}`;
  return dateRangeString;
}

I get tripped up on trying to figure out how to key off that year parameter for MomentJS.

Body:
Instantiate the moment with a date from your desired year

export const getCurrentQuarterRangeString = (quarter, year) => {
  const d = new Date();
  d.setFullYear(year);
  moment = moment(d);

  let start = moment.quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  let end = moment.quarter(quarter).endOf('quarter').format('YYYY-MM-DD');
  let dateRangeString = `${start};#${end}`;
  return dateRangeString;
}


问:
Multi Query for inserting then deleting data
I am struggling to understand how multi queries work.

I want to insert data from one table into another, then delete the data from the original table. How can I do this? Is the method below viable?

<?php

$con =  mysqli_connect('localhost:3308','root','');

if(!$con)
{
    echo 'Not Connected To Server';
}

if(!mysqli_select_db($con, 'Database'))
{
    echo 'Database Not Selected';
}

$jobNumber = $_POST['jobNumberInsert'];
$siteName = $_POST['siteNameInsert'];
$phoneNumber = $_POST['phoneNoInsert'];
$firstName = $_POST['firstNameInsert'];
$lastName = $_POST['lastNameInsert'];
$streetAddress = $_POST['streetAddressInsert'];
$linetwoAddress = $_POST['linetwoAddressInsert'];
$city = $_POST['cityInsert'];
$county = $_POST['countyInsert'];
$postcode = $_POST['postcodeInsert'];
$serviceInfo = $_POST['serviceInfoInsert'];
$jobDate = $_POST['jobDateInsert'];
$priority_value = $_POST['priorityInsert'];

$sql = "INSERT INTO table2(jobNumber,siteName,phoneNumber,firstName,lastName,streetAddress,linetwoAddress,city,county,postcode,serviceInfo,jobDate,priority)
        VALUES ('$jobNumber','$siteName','$phoneNumber','$firstName','$lastName','$streetAddress','$linetwoAddress','$city','$county','$postcode','$serviceInfo','$jobDate','$priority_value')";

$sql .= "DELETE FROM table1 WHERE jobNumber= $jobNumber";

if(!mysqli_multi_query($con,$sql))
{
    echo 'Not Inserted or Deleted';
}
else
{
    echo 'Inserted and Deleted';
}

header("refresh:2 url=index.php");
?>
```

Currently upon executing the code nothing happens. When the statements are executed individually, then they work.

答:
There is no ; (semicolon) after first statement.

```<code>$sql = "INSERT INTO table2(jobNumber,siteName,phoneNumber,firstName,lastName,streetAddress,linetwoAddress,city,county,postcode,serviceInfo,jobDate,priority) VALUES ('$jobNumber','$siteName','$phoneNumber','$firstName','$lastName','$streetAddress','$linetwoAddress','$city','$county','$postcode','$serviceInfo','$jobDate','$priority_value');";
</code>```

So, it's trying to execute as single statement instead of separate statement.

Body:
I am struggling to understand how multi queries work.

I want to insert data from one table into another, then delete the data from the original table. How can I do this? Is the method below viable?

<?php

$con =  mysqli_connect('localhost:3308','root','');

if(!$con)
{
    echo 'Not Connected To Server';
}

if(!mysqli_select_db($con, 'Database'))
{
    echo 'Database Not Selected';
}

$jobNumber = $_POST['jobNumberInsert'];
$siteName = $_POST['siteNameInsert'];
$phoneNumber = $_POST['phoneNoInsert'];
$firstName = $_POST['firstNameInsert'];
$lastName = $_POST['lastNameInsert'];
$streetAddress = $_POST['streetAddressInsert'];
$linetwoAddress = $_POST['linetwoAddressInsert'];
$city = $_POST['cityInsert'];
$county = $_POST['countyInsert'];
$postcode = $_POST['postcodeInsert'];
$serviceInfo = $_POST['serviceInfoInsert'];
$jobDate = $_POST['jobDateInsert'];
$priority_value = $_POST['priorityInsert'];

$sql = "INSERT INTO table2(jobNumber,siteName,phoneNumber,firstName,lastName,streetAddress,linetwoAddress,city,county,postcode,serviceInfo,jobDate,priority)
        VALUES ('$jobNumber','$siteName','$phoneNumber','$firstName','$lastName','$streetAddress','$linetwoAddress','$city','$county','$postcode','$serviceInfo','$jobDate','$priority_value')";

$sql .= "DELETE FROM table1 WHERE jobNumber= $jobNumber";

if(!mysqli_multi_query($con,$sql))
{
    echo 'Not Inserted or Deleted';
}
else
{
    echo 'Inserted and Deleted';
}

header("refresh:2 url=index.php");
?>

Currently upon executing the code nothing happens. When the statements are executed individually, then they work.

Body:
There is no ; (semicolon) after first statement.

$sql = "INSERT INTO table2(jobNumber,siteName,phoneNumber,firstName,lastName,streetAddress,linetwoAddress,city,county,postcode,serviceInfo,jobDate,priority) VALUES ('$jobNumber','$siteName','$phoneNumber','$firstName','$lastName','$streetAddress','$linetwoAddress','$city','$county','$postcode','$serviceInfo','$jobDate','$priority_value');";

So, it's trying to execute as single statement instead of separate statement.


问:
Firestore document stream and update
In the init, of my application I register a stream to one of the documents stored in firestore. Later I update a timestamp field in the same document. I should be getting one callback from the stream since there is only 1 update.

However, I am getting 2 callbacks -

Where that updated field is null

Where that updated field has the correct updated value

Any ideas why?

```<code> CollectionReference collectionReference = FIRESTORE.collection("users");
 if(streamSub == null) {
  streamSub = collectionReference.document(documentID).snapshots().listen((onData){
    onData.data.forEach((k,v) => debugPrint(k + " = " + v.toString()));
  });
 }

//Update field
Firestore.instance
    .collection("users")
    .document(documentID)
    .updateData({"Time" : FieldValue.serverTimestamp() })
</code>```

答:
You're getting two callbacks because of your use of FieldValue.serverTimestamp().  That value is actually a token that gets sent to Firestore servers, where the timestamp is determined and finally written to the database.  Locally on the client, the value isn't known at the time of the write, however, a write of the document still happens in the local cache.

Your listener is first getting the local cache write (before the timestamp is known), then again from the server after the timestamp is known.  You can look at the snapshot metadata to figure out the source of the data if that's important to you.

Title: Firestore document stream and update

Body:
In the init, of my application I register a stream to one of the documents stored in firestore. Later I update a timestamp field in the same document. I should be getting one callback from the stream since there is only 1 update.

However, I am getting 2 callbacks -

Where that updated field is null

Where that updated field has the correct updated value

Any ideas why?

 CollectionReference collectionReference = FIRESTORE.collection("users");
 if(streamSub == null) {
  streamSub = collectionReference.document(documentID).snapshots().listen((onData){
    onData.data.forEach((k,v) => debugPrint(k + " = " + v.toString()));
  });
 }

//Update field
Firestore.instance
    .collection("users")
    .document(documentID)
    .updateData({"Time" : FieldValue.serverTimestamp() })


问:
Force change vue js/css assets hash (fingerprint)
Building vue app in production as in:

```<code>NODE_ENV=production vue-cli-service build
</code>```

Adds the static assets hash fingerprints as below:

```<code>  dist/js/chunk-vendors.d710a916.js      986.81 KiB        297.69 KiB
  dist/js/app.ad3f94f2.js                231.00 KiB        56.02 KiB
  dist/3115008e.worker.js                30.59 KiB         9.98 KiB
  dist/css/app.7eecdb26.css              174.87 KiB        24.16 KiB
  dist/css/chunk-vendors.565b13d4.css    42.77 KiB         6.81 KiB
</code>```

The assets are served with a high maxage cache. Due to some issues involving the headers of these static assets, I want to force renaming all assets, preferably via changing the length of the hash fingerprint (or the algorithm).

So in vue.config.js I added:

```<code>module.exports = {
    configureWebpack: {
        output: {
            hashFunction: 'sha256',
            hashDigestLength: 8,
        },
    ...
}
</code>```

The problem is that it affects only dist/3115008e.worker.js (the hash changes, and length increases to 8). All other assets name remain unchanged.

What changes are required to modify the hash fingerprint length (or algorithm) for the chunk-vendors and app assets?

答:
Update:
I ended up forcing assets hash change by modifying the loader's hashType option in vue.config.js(which seem to default to 'md5'):

```<code>module.exports = {
  ...
  chainWebpack: config => {
    config.module
        .rule('vue')
        .use('vue-loader')
        .loader('vue-loader')
        .tap(options => {
            options.hashType = `sha1`
            return options
        })
},
</code>```

I wasn't able to change the hash length. It seems to be hardcoded in @vue/cli-service": "^4.1.2"

Body:
Building vue app in production as in:

NODE_ENV=production vue-cli-service build

Adds the static assets hash fingerprints as below:

  dist/js/chunk-vendors.d710a916.js      986.81 KiB        297.69 KiB
  dist/js/app.ad3f94f2.js                231.00 KiB        56.02 KiB
  dist/3115008e.worker.js                30.59 KiB         9.98 KiB
  dist/css/app.7eecdb26.css              174.87 KiB        24.16 KiB
  dist/css/chunk-vendors.565b13d4.css    42.77 KiB         6.81 KiB

The assets are served with a high maxage cache. Due to some issues involving the headers of these static assets, I want to force renaming all assets, preferably via changing the length of the hash fingerprint (or the algorithm).

So in vue.config.js I added:

module.exports = {
    configureWebpack: {
        output: {
            hashFunction: 'sha256',
            hashDigestLength: 8,
        },
    ...
}

The problem is that it affects only dist/3115008e.worker.js (the hash changes, and length increases to 8). All other assets name remain unchanged.

What changes are required to modify the hash fingerprint length (or algorithm) for the chunk-vendors and app assets?

Body:
Update:
I ended up forcing assets hash change by modifying the loader's hashType option in vue.config.js(which seem to default to 'md5'):

module.exports = {
  ...
  chainWebpack: config => {
    config.module
        .rule('vue')
        .use('vue-loader')
        .loader('vue-loader')
        .tap(options => {
            options.hashType = `sha1`
            return options
        })
},

I wasn't able to change the hash length. It seems to be hardcoded in @vue/cli-service": "^4.1.2"


问:
How to set validation for drop down in Excel using c# ClosedXML using method List(String list, Boolean inCellDropdown)
Hi All I am trying to create a dropdown list for a column in my excel using ClosedXML library. I am able to create it successfully using the below code.

```<code>      using (XLWorkbook wb = new XLWorkbook())
      {
        wb.Worksheets.Add(dt);
        wb.Worksheets.Add(dt2);
        var worksheet2 = wb.Worksheet(2);
        //wb.Worksheet(1).Column(11).SetDataValidation().List("one,two,three", true); This does not work fine
        wb.Worksheet(1).Column(11).SetDataValidation().List(worksheet2.Range("A2:A12"), true);// Works fine
        wb.Worksheet(1).Column(11).SetDataValidation().IgnoreBlanks = true;
        wb.Worksheet(1).Column(11).SetDataValidation().InCellDropdown = true;
        wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        wb.Style.Font.Bold = true;
        wb.SaveAs(targetFile);
      }
</code>```

But I want to do the same thing with another overloaded method of List in SetDataValidation() but that is creating the excel but when I am trying to open it, it says its corrupted. Could you please help me understand why the other overloaded method is not working.

The method in question is public void List(String list, Boolean inCellDropdown). According to the Data Validation wiki page using a string list is possible :

```<code>//Pass a string in this format: "Option1,Option2,Option3"
var options = new List<string>{"Option1","Option2","Option3"};
var validOptions = $"\"{String.Join(",", options)}\"";
ws.Cell(1,1).DataValidation.List(validOptions, true);
</code>```

答:
According to the Data Validation wiki page, the list list must include the double quotes.

In the doc example :

```<code>var options = new List<string>{"Option1","Option2","Option3"};
var validOptions = $"\"{String.Join(",", options)}\"";
ws.Cell(1,1).DataValidation.List(validOptions, true);
</code>```

validOptions contains :

```<code>"Option1,Option2,Option3"`
</code>```

Your own code should change to :

```<code>.List("\"one,two,three\"", true);
</code>```

Body:
Hi All I am trying to create a dropdown list for a column in my excel using ClosedXML library. I am able to create it successfully using the below code.

      using (XLWorkbook wb = new XLWorkbook())
      {
        wb.Worksheets.Add(dt);
        wb.Worksheets.Add(dt2);
        var worksheet2 = wb.Worksheet(2);
        //wb.Worksheet(1).Column(11).SetDataValidation().List("one,two,three", true); This does not work fine
        wb.Worksheet(1).Column(11).SetDataValidation().List(worksheet2.Range("A2:A12"), true);// Works fine
        wb.Worksheet(1).Column(11).SetDataValidation().IgnoreBlanks = true;
        wb.Worksheet(1).Column(11).SetDataValidation().InCellDropdown = true;
        wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        wb.Style.Font.Bold = true;
        wb.SaveAs(targetFile);
      }

But I want to do the same thing with another overloaded method of List in SetDataValidation() but that is creating the excel but when I am trying to open it, it says its corrupted. Could you please help me understand why the other overloaded method is not working.

The method in question is public void List(String list, Boolean inCellDropdown). According to the Data Validation wiki page using a string list is possible :

//Pass a string in this format: "Option1,Option2,Option3"
var options = new List<string>{"Option1","Option2","Option3"};
var validOptions = $"\"{String.Join(",", options)}\"";
ws.Cell(1,1).DataValidation.List(validOptions, true);

Body:
According to the Data Validation wiki page, the list list must include the double quotes.

In the doc example :

var options = new List<string>{"Option1","Option2","Option3"};
var validOptions = $"\"{String.Join(",", options)}\"";
ws.Cell(1,1).DataValidation.List(validOptions, true);

validOptions contains :

"Option1,Option2,Option3"`

Your own code should change to :

.List("\"one,two,three\"", true);


问:
Laravel: Undefined variable Posts
I am trying to display data using a foreach statement within my system. Now i am passing through the variable 'posts' into my view however i keep receiving the error: Undefined variable: posts (View:.

Search.blade.php

```<code> @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}</option>

 @endforeach
</code>```

SearchController.php

```<code>     public function index()
    {
       $posts = Post::all();
       return view('pages.Search')->with('posts', $posts);

     }
</code>```

Now in my PostsController.php i have similar code which returns all the posts.

PostsController.php

```<code>  public function index()
   {
    $posts = Post::all();
    return view('posts.index')->with('posts', $posts);

}
</code>```

Is this going to cause the error, i didnt think it would cause its returning to a completely separate page.

答:
If you have data in $posts in the controller

Try compact

Like:-
In Controller

```<code>$posts = Post::all();
return view('posts.index', compact('posts');
</code>```

In blade

```<code>@if(count($posts)>0)
 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}.
  </option>
 @endforeach
@else
 <h4>Data not found</h4>
@endif
</code>```

Title: Laravel: Undefined variable Posts

Body:
I am trying to display data using a foreach statement within my system. Now i am passing through the variable 'posts' into my view however i keep receiving the error: Undefined variable: posts (View:.

Search.blade.php

 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}</option>

 @endforeach

SearchController.php

     public function index()
    {
       $posts = Post::all();
       return view('pages.Search')->with('posts', $posts);

     }

Now in my PostsController.php i have similar code which returns all the posts.

PostsController.php

  public function index()
   {
    $posts = Post::all();
    return view('posts.index')->with('posts', $posts);

}

Is this going to cause the error, i didnt think it would cause its returning to a completely separate page.

Body:
If you have data in $posts in the controller

Try compact

Like:-
In Controller

$posts = Post::all();
return view('posts.index', compact('posts');

In blade

@if(count($posts)>0)
 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}.
  </option>
 @endforeach
@else
 <h4>Data not found</h4>
@endif