问:
How to avoid Node.Js app quit when there's a Javascript error?
Suppose I have the following typo in my Node.Js app Javascript code:

    max_weight = Match.floor(max_weight/min_weight)
```

It's supposed to be Math.floor instead of Match.floor so when the code executes I get the error:

ReferenceError: Match is not defined

and then my Node.Js app quits.

How can I ensure that even if an error like this occurs, the app does not quit but simply reports the error and continues the code execution?

I understand I should solve problems like this before launching into production, but, still, what if I want the code to continue the execution despite the error?

答:
By wrapping your code in a try catch block, you should be able to

```<code>try {
  max_weight = Match.floor(max_weight/min_weight);
}
catch(err) {
  // do something to log error
}
</code>```

be aware that the lines inside the try block after where the error is found will not be executed.

Body:
Suppose I have the following typo in my Node.Js app Javascript code:

    max_weight = Match.floor(max_weight/min_weight)

It's supposed to be Math.floor instead of Match.floor so when the code executes I get the error:

ReferenceError: Match is not defined

and then my Node.Js app quits.

How can I ensure that even if an error like this occurs, the app does not quit but simply reports the error and continues the code execution?

I understand I should solve problems like this before launching into production, but, still, what if I want the code to continue the execution despite the error?

Body:
By wrapping your code in a try catch block, you should be able to

try {
  max_weight = Match.floor(max_weight/min_weight);
}
catch(err) {
  // do something to log error
}

be aware that the lines inside the try block after where the error is found will not be executed.


来源: stackexchange

问:
Swift 5. How present or show ViewController on button touch? Without Storyboard (programmatically)
How can I show() or persent() VC on button touch? What code should I write?

答:
First, using Storyboards

If you are working with storyboard. You should connect your button view storyboard.

```<code>@IBAction fileprivate func handlePresentingView(_ sender: UIButton) {
  let vc = SecondVC()
  present(vc, animated: true, completion: nil)
}
</code>```

Second, programmatically

1: If you are working programmatically
in viewDidLoad add the following line.

```<code>    mybutton.addTarget(self, action: #selector(handlePresentingVC(_:)), for: .touchUpInside)
</code>```

2: Your action method

```<code>  @objc func handlePresentingVC(_ sender: UIButton) {
    let vc = SecondVC()
    present(vc, animated: true, completion: nil)
  }
</code>```

In my example, I'm assuming that you don't have a storyboard file for
  your SecondVC view controller.

If SecondVC is connected to a storyboard view controller, you will
  need to change the instantiation of your secondVC object inside of
  your button's action method.

1: Select your SecondVC's view controller in your storyboard.

2: Add a Storyboard ID to it.

3: Change your button's action method to the following.

```<code>  @objc func handlePresentingVC(_ sender: UIButton) {
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let secondVc = storyboard.instantiateViewController(withIdentifier: "SecondVC") as! SecondVC

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

</code>```

In Swift 5 and iOS 13

The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

To retain the old style you need to modify the view controller inside of your button's action method like this:

```<code>secondVc.modalPresentationStyle = .fullScreen
</code>```

This is the same for both programmatically created and storyboard created controllers.

ContentLicense: CC BY-SA 4.0

Body:
First, using Storyboards

If you are working with storyboard. You should connect your button view storyboard.

@IBAction fileprivate func handlePresentingView(_ sender: UIButton) {
  let vc = SecondVC()
  present(vc, animated: true, completion: nil)
}

Second, programmatically

1: If you are working programmatically
in viewDidLoad add the following line.

    mybutton.addTarget(self, action: #selector(handlePresentingVC(_:)), for: .touchUpInside)

2: Your action method

  @objc func handlePresentingVC(_ sender: UIButton) {
    let vc = SecondVC()
    present(vc, animated: true, completion: nil)
  }

In my example, I'm assuming that you don't have a storyboard file for
  your SecondVC view controller.

If SecondVC is connected to a storyboard view controller, you will
  need to change the instantiation of your secondVC object inside of
  your button's action method.

1: Select your SecondVC's view controller in your storyboard.

2: Add a Storyboard ID to it.

3: Change your button's action method to the following.

  @objc func handlePresentingVC(_ sender: UIButton) {
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let secondVc = storyboard.instantiateViewController(withIdentifier: "SecondVC") as! SecondVC

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

In Swift 5 and iOS 13

The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

To retain the old style you need to modify the view controller inside of your button's action method like this:

secondVc.modalPresentationStyle = .fullScreen

This is the same for both programmatically created and storyboard created controllers.


问:
Preserve file last modified date time while copying it from source to target
I am trying to copy a file from one location to another. While copying it from source to target, target file is taking current date time. How can i make target file date as same as source file.</p>

```<code>FileInputStream source = new FileInputStream("D:\\test\\test.txt");
OutputStream target = new FileOutputStream("D:\\test.txt");
byte[] buffer = new byte[source.available()];
source.read(buffer);
target.write(buffer);
source.close();
target.close();`
</code>```

答:
Just use the Path API if you may.

For example to keep all attributes of the original file in the new file, use Files.copy(Path source, Path target, CopyOption... options) :

```<code>try {
   Path copiedFile =
   Files.copy(Paths.get("D:\\test\\test.txt"), Paths.get("D:\\test.txt"),
             StandardCopyOption.COPY_ATTRIBUTES);
}
catch (IOException e){
  // handle that
}
</code>```

The StandardCopyOption.COPY_ATTRIBUTES enum states :

Minimally, the last-modified-time is copied to the target file if
  supported by both the source and target file stores.

If you want to copy only the  last-modified time attribute, that is not more complicated, just add that setting after the copy and remove the CopyOption arg such as :

```<code>Path originalFile = Paths.get("D:\\test.txt")
try {
   Path copiedFile =
   Files.copy(Paths.get("D:\\test\\test.txt"), originalFile);
   Files.setLastModifiedTime(copiedFile,
          Files.getLastModifiedTime(originalFile));
}
catch (IOException e){
  // handle that
}
</code>```

At last, note that Path and File are interoperable : Path.toFile() returns the corresponding File and File.toPath() returns the corresponding Path.

So even if you manipulate Files as input, the implementation may still use the Path API without breaking that.

Body:
I am trying to copy a file from one location to another. While copying it from source to target, target file is taking current date time. How can i make target file date as same as source file.

FileInputStream source = new FileInputStream("D:\\test\\test.txt");
OutputStream target = new FileOutputStream("D:\\test.txt");
byte[] buffer = new byte[source.available()];
source.read(buffer);
target.write(buffer);
source.close();
target.close();`

Body:
Just use the Path API if you may.

For example to keep all attributes of the original file in the new file, use Files.copy(Path source, Path target, CopyOption... options) :

try {
   Path copiedFile =
   Files.copy(Paths.get("D:\\test\\test.txt"), Paths.get("D:\\test.txt"),
             StandardCopyOption.COPY_ATTRIBUTES);
}
catch (IOException e){
  // handle that
}

The StandardCopyOption.COPY_ATTRIBUTES enum states :

Minimally, the last-modified-time is copied to the target file if
  supported by both the source and target file stores.

If you want to copy only the  last-modified time attribute, that is not more complicated, just add that setting after the copy and remove the CopyOption arg such as :

Path originalFile = Paths.get("D:\\test.txt")
try {
   Path copiedFile =
   Files.copy(Paths.get("D:\\test\\test.txt"), originalFile);
   Files.setLastModifiedTime(copiedFile,
          Files.getLastModifiedTime(originalFile));
}
catch (IOException e){
  // handle that
}

At last, note that Path and File are interoperable : Path.toFile() returns the corresponding File and File.toPath() returns the corresponding Path.

So even if you manipulate Files as input, the implementation may still use the Path API without breaking that.


问:
How to get the string from its String.hashCode() value?
I need to somehow get the text from its hash in java.
I have this code:

String myString = new String("creashaks organzine");
int hashCode = myString.hashCode();
System.out.println("Hash:" + hashCode);
```

The result of this code will be 0.
But the hash of "pollinating sandboxes" string will also be 0.

There might be collisions, for example with "creashaks organzine" and "pollinating sandboxes" and I want to find collisions like in this case.

答:
Since i don't have enough reputation to add comment, i will quote solution from another question

You know that several objects can have same hash(), as it mentioned in java doc for Object.hashCode()

It is not required that if two objects are unequal
       *     according to the {@link java.lang.Object#equals(java.lang.Object)}
       *     method, then calling the {@code hashCode} method on each of the
       *     two objects must produce distinct integer results.

It's obvious you can't restore different objects from same hash code, so it's impossible at all, simple logic.

how can I get the String from hashCode

Body:
I need to somehow get the text from its hash in java.
I have this code:

String myString = new String("creashaks organzine");
int hashCode = myString.hashCode();
System.out.println("Hash:" + hashCode);

The result of this code will be 0.
But the hash of "pollinating sandboxes" string will also be 0.

There might be collisions, for example with "creashaks organzine" and "pollinating sandboxes" and I want to find collisions like in this case.


问:
converting back prediction values to original scale(forecasting with python arima model)
i m trying to do some forecasting with ARIMA model. I have a problem converting back my predictions to original scale. here is my code.
can someone help me find the error in my script? I woudl really appreciate it thank you.

```<code>from statsmodels.tsa.arima_model import ARIMA

#arima model
model=ARIMA(ts_logscale,order=(2,1,2))
results_ARIMA=model.fit(disp=-1)
plt.plot(datasetlogdiffshifting)
plt.plot(results_ARIMA.fittedvalues,color='red')
plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-datasetlogdiffshifting["Chargé (T)"])**2))
print('plotting ARIMA model')
</code>```

now, when i try to convert back:

```<code>#converting back
#creating a time serie
predictions_ARIMA_diff=pd.Series(results_ARIMA.fittedvalues,copy=True)
#convert to cumulative sum
predictions_ARIMA_diff_cumsum=predictions_ARIMA_diff.cumsum()

predictions_ARIMA_log=pd.Series(ts_logscale['Chargé (T)'].ix[0],index=ts_logscale.index)
predictions_ARIMA_log=(predictions_ARIMA_log).add(predictions_ARIMA_diff_cumsum,fill_value=0)
#plotting
predictions_ARIMA=np.exp(predictions_ARIMA_log)
plt.plot(ts,color='blue')
plt.plot(predictions_ARIMA,color='red')
</code>```

as u can see it s very different from first plot...

答: ARIMA (2,1,2): is a model with two (2) autoregressive terms, one (1) back shift operator, and two (2) moving average terms. Now, when you apply one (1) back shift operator you don't have to worry because statsmodels models will convert back your predictions, so, the only problem here is the log transformation you did previously, for that, just use np.exp to your predictions and problem solved!</p>

Body:
i m trying to do some forecasting with ARIMA model. I have a problem converting back my predictions to original scale. here is my code.
can someone help me find the error in my script? I woudl really appreciate it thank you.

from statsmodels.tsa.arima_model import ARIMA

#arima model
model=ARIMA(ts_logscale,order=(2,1,2))
results_ARIMA=model.fit(disp=-1)
plt.plot(datasetlogdiffshifting)
plt.plot(results_ARIMA.fittedvalues,color='red')
plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-datasetlogdiffshifting["Chargé (T)"])**2))
print('plotting ARIMA model')

now, when i try to convert back:

#converting back
#creating a time serie
predictions_ARIMA_diff=pd.Series(results_ARIMA.fittedvalues,copy=True)
#convert to cumulative sum
predictions_ARIMA_diff_cumsum=predictions_ARIMA_diff.cumsum()

predictions_ARIMA_log=pd.Series(ts_logscale['Chargé (T)'].ix[0],index=ts_logscale.index)
predictions_ARIMA_log=(predictions_ARIMA_log).add(predictions_ARIMA_diff_cumsum,fill_value=0)
#plotting
predictions_ARIMA=np.exp(predictions_ARIMA_log)
plt.plot(ts,color='blue')
plt.plot(predictions_ARIMA,color='red')

as u can see it s very different from first plot...


问:
Scrape CrawlSpider AttributeError '_rules'
I'm trying to scrape the website of a prominent UK retailer but I am facing an issue with my CrawlSpider - I get the following error message:

AttributeError: 'NlCrawlerSpider' object has no attribute '_rules'

I used the example here to convert my regular spider into a crawl spider; I have also played around with the syntax for the Rules as suggested here but end up with the same error msg. All your help would be much appreciated - thank you in advance!

```<code># Scrapy
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

# Other Packages
import time
from datetime import date
from selenium import webdriver

class NlCrawlerSpider(CrawlSpider):
    name = 'nl_crawler'
    allowed_domains = ['newlook.com']
    start_urls = ['http://www.newlook.com/uk/womens/clothing/c/uk-womens-clothing?comp=NavigationBar%7Cmn%7Cwomens%7Cclothing#/?q=:relevance&page=1&sort=relevance&content=false']

rules = (
    Rule(LinkExtractor(allow=r'\?q=:relevance&page=[1-130]&sort=relevance&content=false', ), callback='parse_item', follow=True),
)

def __init__(self):
    self.driver = webdriver.Safari()
    self.driver.set_window_size(800,600)
    time.sleep(2)

def parse_item(self, response):
    driver = self.driver
    driver.get(response.url)
    time.sleep(2)

    # Collect products
    products = driver.find_elements_by_class_name('plp-item ng-scope')

    # Iterate over products; extract data and append individual features to NlScrapeItem
    for item in products:

        # Pull features
        desc = item.find_element_by_class_name('product-item__name link--nounderline ng-binding').text
        href = item.find_element_by_class_name('plp-carousel__img-link ng-scope').get_attribute('href')

        # Generate a product identifier
        identifier = href.split('/p/')[1].split('?comp')[0]
        identifier = int(identifier)

        # datetime
        dt = date.today()
        dt = dt.isoformat()

        # Price Symbol removal and integer conversion
        try:
            priceString = item.find_element_by_class_name('price ng-binding').text
        except:
            priceString = item.find_element_by_class_name('price price--previous-price product-item__price--previous-price ng-binding ng-scope').text
        priceInt = priceString.split('£')[1]
        originalPrice = float(priceInt)

        # discountedPrice Logic
        try:
            discountedPriceString = item.find_element_by_class_name('price ng-binding price--marked-down').text
            discountedPriceInt = discountedPriceString.split('£')[1]
            discountedPrice = float(discountedPriceInt)
        except:
            discountedPrice = 'N/A'

        # NlScrapeItem
        item = NlScrapeItem()

        # Append product to NlScrapeItem
        item['identifier'] = identifier
        item['href'] = href
        item['description'] = desc
        item['originalPrice'] = originalPrice
        item['discountedPrice'] = discountedPrice
        item['firstSighted'] = dt
        item['lastSighted'] = dt

        yield item
</code>```

Additions:
So I tried to ignore the idea of using a crawlSpider and follow @jabargas thinking - see below:

```<code>def __init__(self):
    self.driver = webdriver.Safari()
    self.driver.set_window_size(800,600)

def start_requests(self):
    n = 5
    urls= []
    for pageNumber in range(1,n):
            url = 'http://www.newlook.com/uk/womens/clothing/c/uk-womens-clothing?comp=NavigationBar%%7Cmn%%7Cwomens%%7Cclothing#/?q=:relevance&page=%d&sort=relevance&content=false' % pageNumber
            urls.append(url)

    for url in urls:
        yield scrapy.Request(url=url, callback=self.parse)

def parse(self, response):
    driver = self.driver
    driver.get(response.url)
    time.sleep(2)

    # Collect products
    products = driver.find_elements_by_class_name('plp-item ng-scope')

    # Iterate over products; extract data and append individual features to NlScrapeItem
    for item in products:

        # Pull features
        desc = item.find_element_by_class_name('product-item__name link--nounderline ng-binding').text
        href = item.find_element_by_class_name('plp-carousel__img-link ng-scope').get_attribute('href')

        # Generate a product identifier
        identifier = href.split('/p/')[1].split('?comp')[0]
        identifier = int(identifier)

        # datetime
        dt = date.today()
        dt = dt.isoformat()

        # Price Symbol removal and integer conversion
        try:
            priceString = item.find_element_by_class_name('price ng-binding').text
        except:
            priceString = item.find_element_by_class_name('price price--previous-price product-item__price--previous-price ng-binding ng-scope').text
        priceInt = priceString.split('£')[1]
        originalPrice = float(priceInt)

        # discountedPrice Logic
        try:
            discountedPriceString = item.find_element_by_class_name('price ng-binding price--marked-down').text
            discountedPriceInt = discountedPriceString.split('£')[1]
            discountedPrice = float(discountedPriceInt)
        except:
            discountedPrice = 'N/A'

        # NlScrapeItem
        item = NlScrapeItem()

        # Append product to NlScrapeItem
        item['identifier'] = identifier
        item['href'] = href
        item['description'] = desc
        item['originalPrice'] = originalPrice
        item['discountedPrice'] = discountedPrice
        item['firstSighted'] = dt
        item['lastSighted'] = dt

        yield item
</code>```

Unfortunately no luck: it pulls details for 48 items.

答:
Another possible issue is that you have not added super constructor in your init method.

add "super(MySpider, self).init(*a, **kw)" for it.

I got the same issue and fixed it by that.

so init should look like follows

```<code>def __init__(self, *a, **kw):
    super(MySpider, self).__init__(*a, **kw)
    //your initializations
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to scrape the website of a prominent UK retailer but I am facing an issue with my CrawlSpider - I get the following error message:

AttributeError: 'NlCrawlerSpider' object has no attribute '_rules'

I used the example here to convert my regular spider into a crawl spider; I have also played around with the syntax for the Rules as suggested here but end up with the same error msg. All your help would be much appreciated - thank you in advance!

# Scrapy
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

# Other Packages
import time
from datetime import date
from selenium import webdriver

class NlCrawlerSpider(CrawlSpider):
    name = 'nl_crawler'
    allowed_domains = ['newlook.com']
    start_urls = ['http://www.newlook.com/uk/womens/clothing/c/uk-womens-clothing?comp=NavigationBar%7Cmn%7Cwomens%7Cclothing#/?q=:relevance&page=1&sort=relevance&content=false']

rules = (
    Rule(LinkExtractor(allow=r'\?q=:relevance&page=[1-130]&sort=relevance&content=false', ), callback='parse_item', follow=True),
)

def __init__(self):
    self.driver = webdriver.Safari()
    self.driver.set_window_size(800,600)
    time.sleep(2)

def parse_item(self, response):
    driver = self.driver
    driver.get(response.url)
    time.sleep(2)

    # Collect products
    products = driver.find_elements_by_class_name('plp-item ng-scope')

    # Iterate over products; extract data and append individual features to NlScrapeItem
    for item in products:

        # Pull features
        desc = item.find_element_by_class_name('product-item__name link--nounderline ng-binding').text
        href = item.find_element_by_class_name('plp-carousel__img-link ng-scope').get_attribute('href')

        # Generate a product identifier
        identifier = href.split('/p/')[1].split('?comp')[0]
        identifier = int(identifier)

        # datetime
        dt = date.today()
        dt = dt.isoformat()

        # Price Symbol removal and integer conversion
        try:
            priceString = item.find_element_by_class_name('price ng-binding').text
        except:
            priceString = item.find_element_by_class_name('price price--previous-price product-item__price--previous-price ng-binding ng-scope').text
        priceInt = priceString.split('£')[1]
        originalPrice = float(priceInt)

        # discountedPrice Logic
        try:
            discountedPriceString = item.find_element_by_class_name('price ng-binding price--marked-down').text
            discountedPriceInt = discountedPriceString.split('£')[1]
            discountedPrice = float(discountedPriceInt)
        except:
            discountedPrice = 'N/A'

        # NlScrapeItem
        item = NlScrapeItem()

        # Append product to NlScrapeItem
        item['identifier'] = identifier
        item['href'] = href
        item['description'] = desc
        item['originalPrice'] = originalPrice
        item['discountedPrice'] = discountedPrice
        item['firstSighted'] = dt
        item['lastSighted'] = dt

        yield item

Additions:
So I tried to ignore the idea of using a crawlSpider and follow @jabargas thinking - see below:

def __init__(self):
    self.driver = webdriver.Safari()
    self.driver.set_window_size(800,600)

def start_requests(self):
    n = 5
    urls= []
    for pageNumber in range(1,n):
            url = 'http://www.newlook.com/uk/womens/clothing/c/uk-womens-clothing?comp=NavigationBar%%7Cmn%%7Cwomens%%7Cclothing#/?q=:relevance&page=%d&sort=relevance&content=false' % pageNumber
            urls.append(url)

    for url in urls:
        yield scrapy.Request(url=url, callback=self.parse)

def parse(self, response):
    driver = self.driver
    driver.get(response.url)
    time.sleep(2)

    # Collect products
    products = driver.find_elements_by_class_name('plp-item ng-scope')

    # Iterate over products; extract data and append individual features to NlScrapeItem
    for item in products:

        # Pull features
        desc = item.find_element_by_class_name('product-item__name link--nounderline ng-binding').text
        href = item.find_element_by_class_name('plp-carousel__img-link ng-scope').get_attribute('href')

        # Generate a product identifier
        identifier = href.split('/p/')[1].split('?comp')[0]
        identifier = int(identifier)

        # datetime
        dt = date.today()
        dt = dt.isoformat()

        # Price Symbol removal and integer conversion
        try:
            priceString = item.find_element_by_class_name('price ng-binding').text
        except:
            priceString = item.find_element_by_class_name('price price--previous-price product-item__price--previous-price ng-binding ng-scope').text
        priceInt = priceString.split('£')[1]
        originalPrice = float(priceInt)

        # discountedPrice Logic
        try:
            discountedPriceString = item.find_element_by_class_name('price ng-binding price--marked-down').text
            discountedPriceInt = discountedPriceString.split('£')[1]
            discountedPrice = float(discountedPriceInt)
        except:
            discountedPrice = 'N/A'

        # NlScrapeItem
        item = NlScrapeItem()

        # Append product to NlScrapeItem
        item['identifier'] = identifier
        item['href'] = href
        item['description'] = desc
        item['originalPrice'] = originalPrice
        item['discountedPrice'] = discountedPrice
        item['firstSighted'] = dt
        item['lastSighted'] = dt

        yield item

Unfortunately no luck: it pulls details for 48 items.

Body:
Another possible issue is that you have not added super constructor in your init method.

add "super(MySpider, self).init(*a, **kw)" for it.

I got the same issue and fixed it by that.

so init should look like follows

def __init__(self, *a, **kw):
    super(MySpider, self).__init__(*a, **kw)
    //your initializations


问:
Apache Spark 2.0 Model Persistence
According to this post: https://databricks.com/blog/2016/05/31/apache-spark-2-0-preview-machine-learning-model-persistence.html
Spark 2.0 includes a language independent model serialization.

Does this support the use case of training a model using spark, and serving the model in a non jvm language (like python without jvm backend, as used in pyspark)?

答:
Deploying spark mllib models and model pipelines in a non spark environment can be solved by using third party libraries like MLeap.

MLeap packages your code into binaries that can be deployed outside of spark using MLeap model import. It has good backward compatibility with MLeap, so as you update your spark and MLeap versions, the previous versions of MLeap will still continue to work, as of now, spark doesn't guarantee this over major releases.

Title: Apache Spark 2.0 Model Persistence


问:
Is a product backlog related with the domain model?
Is a product backlog related with the domain model in a DDD aproach or I'm mixing unrelated concepts?</p>

答:
Scrum doesn't prescribe exactly how you express Product Backlog Items. You can use User Stories, Job Stories or your own custom thing. As long as your Product Backlog Items have the following attributes (from the Scrum Guide):

"The Product Backlog lists all features, functions, requirements, enhancements, and fixes that constitute the changes to be made to the product in future releases. Product Backlog items have the attributes of a description, order, estimate, and value. Product Backlog items often include test descriptions that will prove its completeness when "Done"." - Scrum Guide

How these Product Backlog Items are picked up and broken down in smaller chunks of work in the Sprint, is up to the Development Team. They can use whatever approach they want. As long as the resulting chunks of work are small enough to fit in a Sprint.


问:
Adding a Combobox in DataGridView through Datatable
I have a DataGridView and I am populating it through a DataTable. On initializing, I add DataColumns to the DataTable and then set the DataSource of the DataGridView to the DataTable. Here is the code:

```<code>DataTable mTable    = new DataTable("Test");

DataColumn  col = new DataColumn;
col.DataType      = System.Type.GetType("System.Boolean");
col.ColumnName  = "First";
col.ReadOnly    = false;
mTable.Columns.Add(col);

col            = new DataColumn;
col.DataType    = System.Type.GetType("System.String");
col.ColumnName  = "Second";
col.ReadOnly    = false;
mTable.Columns.Add(col);

this.myGridView.DataSource = mTable;
</code>```

This works fine however, I want to make one of the columns showup as a combobox. I think I have to do something with the Column's datatype but I am not sure how to do this. Can anyone give me any pointer towards this?

答:
This is old, but I thought I'd try to answer it anyways since I had the same question myself a while ago.

First of all, you cannot make a DataTable column of type DataGridViewComboBoxColumn.  DataColumn inherits from System.Data, while DataGridView*Columns inherit from System.Windows.Forms.

What you can try is this:  Once your DataTable is bound to your DataGridView, the columns from the DataTable should show up on the DataGridView in the designer.  If you then expand the Columns property of your DataGridView, you should see your columns from your DataTable have been added to the list.  Select the column that you want, and in the right-hand pane there will be a property called 'ColumnType'.  The default type is DataGridViewTextBoxColumn, but you can change it to DataGridViewComboBoxColumn.

ContentLicense: CC BY-SA 2.5

Body:
I have a DataGridView and I am populating it through a DataTable. On initializing, I add DataColumns to the DataTable and then set the DataSource of the DataGridView to the DataTable. Here is the code:

DataTable mTable    = new DataTable("Test");

DataColumn  col = new DataColumn;
col.DataType      = System.Type.GetType("System.Boolean");
col.ColumnName  = "First";
col.ReadOnly    = false;
mTable.Columns.Add(col);

col            = new DataColumn;
col.DataType    = System.Type.GetType("System.String");
col.ColumnName  = "Second";
col.ReadOnly    = false;
mTable.Columns.Add(col);

this.myGridView.DataSource = mTable;

This works fine however, I want to make one of the columns showup as a combobox. I think I have to do something with the Column's datatype but I am not sure how to do this. Can anyone give me any pointer towards this?


问:
Asp.Net Core Api Default Routing
I have a very basic Asp.Net Core Api; my controller looks like this:

```<code>[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public IEnumerable<Resource> Test(string id)
    {
         // Breakpoint here
    }
</code>```

I would expect the following URL to invoke the method, and fire the breakpoint:

```<code>https://localhost:5012/test/test/1
</code>```

However, it doesn't. In fact, the following URL does:

```<code>https://localhost:5012/test/1
</code>```

I was under the impression that the format for the URL was as follows (from startup):

```<code>app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
});
</code>```

So, unless that action is Index:

```<code>https://localhost:5012/controller/action/id
</code>```

But it appears that the accepted format is:

```<code>https://localhost:5012/controller/id
</code>```

My question is, why is this?

答:
In addition to pwrigshihanomoronimo answer,

you can just change this

```<code>[HttpGet("{id}")]
public IEnumerable<Resource> Test(string id)
</code>```

to

```<code>[HttpGet("[action]/{id}")]
public IEnumerable<Resource> Test(string id)
</code>```

Title: Asp.Net Core Api Default Routing

Body:
I have a very basic Asp.Net Core Api; my controller looks like this:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public IEnumerable<Resource> Test(string id)
    {
         // Breakpoint here
    }

I would expect the following URL to invoke the method, and fire the breakpoint:

https://localhost:5012/test/test/1

However, it doesn't. In fact, the following URL does:

https://localhost:5012/test/1

I was under the impression that the format for the URL was as follows (from startup):

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
});

So, unless that action is Index:

https://localhost:5012/controller/action/id

But it appears that the accepted format is:

https://localhost:5012/controller/id

My question is, why is this?

Body:
In addition to pwrigshihanomoronimo answer,

you can just change this

[HttpGet("{id}")]
public IEnumerable<Resource> Test(string id)

to

[HttpGet("[action]/{id}")]
public IEnumerable<Resource> Test(string id)


问:
I can't seem to link html to css
```<code>    <!DOCTYPE html>
<html>
  <head>
    <link href="style.css" rel="designpage" type="text/css">
    <title> Viktoria Niemann </title>
  </head>
  <body>
    <h1>Dear Vik</h1>
    <ul>
      <li><a href= "index.html">Home</a></li>
      <li><a href="about.html">About</a></li>
      <li><a href="gallery.html">Gallery</a></li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
    <img src="https://upload.wikimedia.org/wikipedia/commons/3/33/-LOVE-love-36983825-1680-1050.jpg">

  </body>
</html>
</code>```

I am not sure why html is not linking to css. I think i have written a code correctly

答:
make your rel "stylesheet" like this ------> rel="stylesheet"

<link href="style.css" rel="stylesheet" type="text/css">```

Title: I can't seem to link html to css

Body:
    <!DOCTYPE html>

    <link href="style.css" rel="designpage" type="text/css">
    <title> Viktoria Niemann </title>

Dear Vik

Home

About

Gallery

Contact

I am not sure why html is not linking to css. I think i have written a code correctly


问:
Python Installing Modules on Mac OS
I am new to Python and terminal prompts/installs and I keep running into installation errors when trying to install modules like Pandas.

I have successfully installed  "pip install pandas"
I am unable to install this with pip3 however.

```<code>Collecting pandas
  Could not find a version that satisfies the requirement pandas (from versions: )
No matching distribution found for pandas
</code>```

I have pip3 installed and python3(this comes with mac os).
I do not understand the conflict between the versions. If I install using pip, its only compatible with python2?
Why wouldnt I be able to install it using pip3 (see error above)?

Am I somehow installing in the wrong directories or not making the correct distinction for python3 and pip3 version compatibility? Thanks for any insight.

答:
As already said in the comments, pip installs modules for python2. Also, you can't run pandas as a command on the shell.

pip3 install pandas works for me, on python3 (v3.7.4), which was installed directly from a Mac installer package on the python website.  No 'environment configuration' was required.

```<code>>pip3 install pandas
Collecting pandas
  Downloading https://files.pythonhosted.org/packages/ab/ba/f97030b7e8ec0a981abdca173de4e727b3a7b4ed5dba492f362ba87d59a2/pandas-1.0.1-cp37-cp37m-macosx_10_9_x86_64.whl (9.8MB)
    100% |████████████████████████████████| 9.8MB 2.8MB/s
</code>```

If you've installed python3 using some different method, then you may need to install packages differently or configure your python installation in some way.

Title: Python Installing Modules on Mac OS

Body:
I am new to Python and terminal prompts/installs and I keep running into installation errors when trying to install modules like Pandas.

I have successfully installed  "pip install pandas"
I am unable to install this with pip3 however.

Collecting pandas
  Could not find a version that satisfies the requirement pandas (from versions: )
No matching distribution found for pandas

I have pip3 installed and python3(this comes with mac os).
I do not understand the conflict between the versions. If I install using pip, its only compatible with python2?
Why wouldnt I be able to install it using pip3 (see error above)?

Am I somehow installing in the wrong directories or not making the correct distinction for python3 and pip3 version compatibility? Thanks for any insight.

Body:
As already said in the comments, pip installs modules for python2. Also, you can't run pandas as a command on the shell.

pip3 install pandas works for me, on python3 (v3.7.4), which was installed directly from a Mac installer package on the python website.  No 'environment configuration' was required.

>pip3 install pandas
Collecting pandas
  Downloading https://files.pythonhosted.org/packages/ab/ba/f97030b7e8ec0a981abdca173de4e727b3a7b4ed5dba492f362ba87d59a2/pandas-1.0.1-cp37-cp37m-macosx_10_9_x86_64.whl (9.8MB)
    100% |████████████████████████████████| 9.8MB 2.8MB/s

If you've installed python3 using some different method, then you may need to install packages differently or configure your python installation in some way.


问:
Android build.gradle ERROR: ParseError at [row,col]:[65,9] Message: expected start or end tag Affected Modules: app
build.gradle:

Android build.gradle shows following error

```<code>ERROR: ParseError at [row,col]:[65,9] Message: expected start or end tag Affected Modules: app
</code>```

答: also had the same error. just look at the location [row] at the Manifest file and fix the problem (I had extra ">")

Body:
build.gradle:

Android build.gradle shows following error

ERROR: ParseError at [row,col]:[65,9] Message: expected start or end tag Affected Modules: app


问:
Best practice of Receiving bulk of data [laravel Restfult API]
I have a case of receiving bulk of data to handle it in APIs

what's the best practice of receiving it

First approach => create multiple array each hold the data of each field

```<code>$names = ['SAM','John','Vardy'];

$ages = ['19','20','22'];
</code>```

or
Second approach => create one array each index has it own object

```<code>$data = [
   {
     'name':'SAM',
     'age':'19'
   },
   {
     'name':'John',
     'age':'20'
   },
   {
     'name':'Vardy',
     'age':'22'
   },
];
</code>```

what's the best one of them ???

答: This really depends on your needs, but for me, the second approach seems more consistent.</p>

Body:
I have a case of receiving bulk of data to handle it in APIs

what's the best practice of receiving it

First approach => create multiple array each hold the data of each field

$names = ['SAM','John','Vardy'];

$ages = ['19','20','22'];

or
Second approach => create one array each index has it own object

$data = [
   {
     'name':'SAM',
     'age':'19'
   },
   {
     'name':'John',
     'age':'20'
   },
   {
     'name':'Vardy',
     'age':'22'
   },
];

what's the best one of them ???


问:
Scheme::R5RS. I'm studying lambda and I don't understand these codes
```
I'm studying lambda for my midterm and I understand the concept.

**the lambda function is just a way of defining a function without giving it a name.
**the lambda format has to be ((lambda (x y z) (formula) parameter)
**please fix me if I'm wrong.

I don't understand the codes below.
Can someone explain to me why the answer is like that?
I know it's a lot, you don't have to explain all the examples.
Thanks!
```

```<code>((lambda (x y z)(x(/ y 2)(* 3 z)6))+ 4 2)                   ;14
((lambda (x)((lambda (x)(/ x 4))(+ x 2)))6)                 ;2
((lambda (x y)(+ (x * y)(x + y)))(lambda (x y)(x y y ))3)   ;15
(((lambda (a)(lambda (b) '(lambda (c) '(a b c)))) 1) 2)
(((lambda(x)(lambda(y)(+ x y))) 12) ((lambda(z)(* 3 z)) 3))
(define (x y z)((lambda (y z)(- y z)) z y)) (x 3 5)
((lambda (x y) (+ 3 x (* 2 y))) (+ 3 3)(* 2 2))
((lambda(x)(lambda(y)(+ x y)))12)
</code>```

答:
You can easily rewrite a lambda to a let. Eg.

```<code>((lambda (x y z)
   (x (/ y 2)
      (* 3 z)
      6))
 +
 4
 2)
</code>```

As let:

```<code>(let ((x +) (y 4) (z 2))
  (x (/ y 2)
     (* 3 z)
     6))
</code>```

It is the exact same code but perhaps slightly more readable. Every lambda for that gets called immediately can get that treatment also after substitution steps.
Now you can use the substitution rules. Replace x with +, y with 4 and z with 2 and replace the call/let with the same expression with the values replaced:

```<code>(+ (/ 4 2)
   (* 3 2)
   6))
</code>```

Substitute simple expressions with their result:

```<code>(+ 2
   6
   6))
; ==> 14
</code>```

And there you go. Easy peasy.

Body:
I'm studying lambda for my midterm and I understand the concept.

**the lambda function is just a way of defining a function without giving it a name.
**the lambda format has to be ((lambda (x y z) (formula) parameter)
**please fix me if I'm wrong.

I don't understand the codes below.
Can someone explain to me why the answer is like that?
I know it's a lot, you don't have to explain all the examples.
Thanks!

((lambda (x y z)(x(/ y 2)(* 3 z)6))+ 4 2)                   ;14
((lambda (x)((lambda (x)(/ x 4))(+ x 2)))6)                 ;2
((lambda (x y)(+ (x * y)(x + y)))(lambda (x y)(x y y ))3)   ;15
(((lambda (a)(lambda (b) '(lambda (c) '(a b c)))) 1) 2)
(((lambda(x)(lambda(y)(+ x y))) 12) ((lambda(z)(* 3 z)) 3))
(define (x y z)((lambda (y z)(- y z)) z y)) (x 3 5)
((lambda (x y) (+ 3 x (* 2 y))) (+ 3 3)(* 2 2))
((lambda(x)(lambda(y)(+ x y)))12)

Body:
You can easily rewrite a lambda to a let. Eg.

((lambda (x y z)
   (x (/ y 2)
      (* 3 z)
      6))
 +
 4
 2)

As let:

(let ((x +) (y 4) (z 2))
  (x (/ y 2)
     (* 3 z)
     6))

It is the exact same code but perhaps slightly more readable. Every lambda for that gets called immediately can get that treatment also after substitution steps.
Now you can use the substitution rules. Replace x with +, y with 4 and z with 2 and replace the call/let with the same expression with the values replaced:

(+ (/ 4 2)
   (* 3 2)
   6))

Substitute simple expressions with their result:

(+ 2
   6
   6))
; ==> 14

And there you go. Easy peasy.


问:
Ionic 4 Http failure response for (unknown url): 0 Unknown Error. when calling api on real device
I have an ionic 4 application which calls a .NET Core backend api.
It works correctly on chrome browser, but when I run apk on android device, the response is:

```<code>{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}
</code>```

regarding to header I appended these options:

```<code>const httpOptions = {
    headers: new HttpHeaders({
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" ,
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token, Accept, Authorization, X-Request-With",
        "Access-Control-Allow-Credentials" : "true",
        "Access-Control-Allow-Methods" : "GET, POST, DELETE, PUT, OPTIONS, TRACE, PATCH, CONNECT"
       })
};
</code>```

I have already installed plugin:
cordova-plugin-ionic-webview

and using HttpClient from "@angular/common/http"

My API hosted remotely, no ssl certificate used !

I googled all solutions, but none of them solve my problem

答: localhost does not support any android app. If you try to hit API with localhost then, android considers localhost 0.0.0.0:</p>

Body:
I have an ionic 4 application which calls a .NET Core backend api.
It works correctly on chrome browser, but when I run apk on android device, the response is:

{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}

regarding to header I appended these options:

const httpOptions = {
    headers: new HttpHeaders({
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" ,
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token, Accept, Authorization, X-Request-With",
        "Access-Control-Allow-Credentials" : "true",
        "Access-Control-Allow-Methods" : "GET, POST, DELETE, PUT, OPTIONS, TRACE, PATCH, CONNECT"
       })
};

I have already installed plugin:
cordova-plugin-ionic-webview

and using HttpClient from "@angular/common/http"

My API hosted remotely, no ssl certificate used !

I googled all solutions, but none of them solve my problem


问:
SQL query joining two different tables. Find online status from user's last interaction
Problem description: Finding online status of therapist users based on  last interaction in Session table. Cannot keep last interaction date on User table but it should be separated on Session table. But how can I join one row for each user with User table information and session data of Session table for user's last interaction for each record?

Description of figure 1: Listing of therapists from User table with showing their online status based on their last interaction from Session table

Description of figure2 (User): User table is the first table and email is its primary key. It need to be joined with second column, that is Session table's StartDate field as one row for each record. (Pink backgrounded StartDate column is not on User table. User table columns plus the pink backgrounded StartDate column is desired result)

The hardest part of the problem is email is basis of join field and only one in User table but has many in the Session table because it is not primary there.

Description of figure3 (Session): Email field duplicates as user interacts in the program. They are kind of logs of key presses changing personal information e.g.

I cannot created a qualified query to solve my problem so I created a query for table1 and second query in the loop that is not right way of doing the job. It caused performance issues. I need to get help joining two different queries at once.

The first query filters results based on primary key email from User table. The second query gets latest session date on from Session table within the loop.

$marker_list is the first query and $sql_online is for the second query which is nested.

```<code><?php

$latitude = filter_input(INPUT_GET, "latitude", FILTER_SANITIZE_SPECIAL_CHARS);
$longitude = filter_input(INPUT_GET, "longitude", FILTER_SANITIZE_SPECIAL_CHARS);
$start = filter_input(INPUT_GET, "start", FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_GET, "email", FILTER_SANITIZE_EMAIL);

include_once "./connect-db.php";

if ($start == 'undefined') {
    $start = 0;
} else {
    $start = $start * 10;
}
$distance = 100;
//First query: lists therapists from User table
$marker_list = "SELECT `User`.`uid`, `User`.`latitude`, `User`.`longitude`, `User`.`name`, `User`.`phone_verified`, `User`.`email`, ( 3959 * acos(cos(radians(" . $latitude . ")) * cos(radians(latitude)) * cos(radians(longitude) - radians(" . $longitude . ")) + sin(radians(" . $latitude . ")) * sin(radians(latitude ))) ) AS `distance` FROM `massage`.`User` WHERE rol= 'terapist' AND list_on_maps= '1' AND email_valid='1' HAVING distance < $distance ORDER BY distance LIMIT $start, 7";

if ($results = mysqli_query($conn, $marker_list)) {
     $sizeofquery = mysqli_num_rows($results);
     $counter = 0;
     $maps = array();
     while ($row = mysqli_fetch_row($results)) {
         $maps[$counter] = new stdClass();
         $maps[$counter]->index = $row[0];
         $maps[$counter]->latlng = new stdClass();
         $maps[$counter]->latlng->latitude = floatval($row[1]);
         $maps[$counter]->latlng->longitude = floatval($row[2]);
         $maps[$counter]->title = $row[3];
         $maps[$counter]->phone_verified = $row[4];
//Second query gets their user interaction from Session table
         $sql_online= "SELECT `StartDate` FROM `massage`.`Session` WHERE `email`='$row[5]' ORDER BY `Session`.`StartDate` DESC LIMIT 1";
         $result_nested= mysqli_query($conn, $sql_online);
         $row_online= mysqli_fetch_array($result_nested);
         $delta= (strtotime("now") - strtotime($row_online['StartDate']));
         if ($delta < 300 ) {
             $maps[$counter]->online = "y";
         } else if ( $delta < 600){
             $maps[$counter]->online = "t";
         } else {
             $maps[$counter]->online = "g";
         }
         $counter++;
    }
    $maps->counter = $row['counter'];
    $mapsJSON = json_encode($maps);
}
//Third Query: Inserts last interaction as listing therapists as on many pages. It is not an important part of the question.
$sql_session = "INSERT INTO `massage`.`Session` (`StartDate`, `email`, `Interaction`) VALUES (current_timestamp(), '$email', 'dolistmaps');";
mysqli_query($conn, $sql_session);
header('Content-type:application/json;charset=utf-8');
echo $mapsJSON;
mysqli_free_result($results);
mysqli_close($conn);
</code>```

So please help me creating a single query which accomplishes joining two different tables on the common field  email on both tables.

答:
The SQL syntax for joining two tables is using JOIN keyword. Two tables with a common column could be joined with this syntax:

```<code>select StartDate
from Masage.Session masag
inner join User user on masag.email = user.email
</code>```

This is for inner join. If you want left outer join or right outer join, or maybe full outer join or even cross join you shall replace the join cause with a proper keywords. I hope I did answer your question.

Body:
Problem description: Finding online status of therapist users based on  last interaction in Session table. Cannot keep last interaction date on User table but it should be separated on Session table. But how can I join one row for each user with User table information and session data of Session table for user's last interaction for each record?

Description of figure 1: Listing of therapists from User table with showing their online status based on their last interaction from Session table

Description of figure2 (User): User table is the first table and email is its primary key. It need to be joined with second column, that is Session table's StartDate field as one row for each record. (Pink backgrounded StartDate column is not on User table. User table columns plus the pink backgrounded StartDate column is desired result)

The hardest part of the problem is email is basis of join field and only one in User table but has many in the Session table because it is not primary there.

Description of figure3 (Session): Email field duplicates as user interacts in the program. They are kind of logs of key presses changing personal information e.g.

I cannot created a qualified query to solve my problem so I created a query for table1 and second query in the loop that is not right way of doing the job. It caused performance issues. I need to get help joining two different queries at once.

The first query filters results based on primary key email from User table. The second query gets latest session date on from Session table within the loop.

$marker_list is the first query and $sql_online is for the second query which is nested.

<?php

$latitude = filter_input(INPUT_GET, "latitude", FILTER_SANITIZE_SPECIAL_CHARS);
$longitude = filter_input(INPUT_GET, "longitude", FILTER_SANITIZE_SPECIAL_CHARS);
$start = filter_input(INPUT_GET, "start", FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_GET, "email", FILTER_SANITIZE_EMAIL);

include_once "./connect-db.php";

if ($start == 'undefined') {
    $start = 0;
} else {
    $start = $start * 10;
}
$distance = 100;
//First query: lists therapists from User table
$marker_list = "SELECT `User`.`uid`, `User`.`latitude`, `User`.`longitude`, `User`.`name`, `User`.`phone_verified`, `User`.`email`, ( 3959 * acos(cos(radians(" . $latitude . ")) * cos(radians(latitude)) * cos(radians(longitude) - radians(" . $longitude . ")) + sin(radians(" . $latitude . ")) * sin(radians(latitude ))) ) AS `distance` FROM `massage`.`User` WHERE rol= 'terapist' AND list_on_maps= '1' AND email_valid='1' HAVING distance < $distance ORDER BY distance LIMIT $start, 7";

if ($results = mysqli_query($conn, $marker_list)) {
     $sizeofquery = mysqli_num_rows($results);
     $counter = 0;
     $maps = array();
     while ($row = mysqli_fetch_row($results)) {
         $maps[$counter] = new stdClass();
         $maps[$counter]->index = $row[0];
         $maps[$counter]->latlng = new stdClass();
         $maps[$counter]->latlng->latitude = floatval($row[1]);
         $maps[$counter]->latlng->longitude = floatval($row[2]);
         $maps[$counter]->title = $row[3];
         $maps[$counter]->phone_verified = $row[4];
//Second query gets their user interaction from Session table
         $sql_online= "SELECT `StartDate` FROM `massage`.`Session` WHERE `email`='$row[5]' ORDER BY `Session`.`StartDate` DESC LIMIT 1";
         $result_nested= mysqli_query($conn, $sql_online);
         $row_online= mysqli_fetch_array($result_nested);
         $delta= (strtotime("now") - strtotime($row_online['StartDate']));
         if ($delta < 300 ) {
             $maps[$counter]->online = "y";
         } else if ( $delta < 600){
             $maps[$counter]->online = "t";
         } else {
             $maps[$counter]->online = "g";
         }
         $counter++;
    }
    $maps->counter = $row['counter'];
    $mapsJSON = json_encode($maps);
}
//Third Query: Inserts last interaction as listing therapists as on many pages. It is not an important part of the question.
$sql_session = "INSERT INTO `massage`.`Session` (`StartDate`, `email`, `Interaction`) VALUES (current_timestamp(), '$email', 'dolistmaps');";
mysqli_query($conn, $sql_session);
header('Content-type:application/json;charset=utf-8');
echo $mapsJSON;
mysqli_free_result($results);
mysqli_close($conn);

So please help me creating a single query which accomplishes joining two different tables on the common field  email on both tables.

Body:
The SQL syntax for joining two tables is using JOIN keyword. Two tables with a common column could be joined with this syntax:

select StartDate
from Masage.Session masag
inner join User user on masag.email = user.email

This is for inner join. If you want left outer join or right outer join, or maybe full outer join or even cross join you shall replace the join cause with a proper keywords. I hope I did answer your question.


答:
Try this:</p>

```<code><!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css" type="text/css">
    <title> Viktoria Niemann </title>
</head>

<body>
    <h1>Dear Vik</h1>
    <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="gallery.html">Gallery</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
    <img src="https://upload.wikimedia.org/wikipedia/commons/3/33/-LOVE-love-36983825-1680-1050.jpg">

</body>

</html>
</code>```

Title: I can't seem to link html to css

Body:
Try this:

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css" type="text/css">
    <title> Viktoria Niemann </title>
</head>

<body>
    <h1>Dear Vik</h1>
    <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="gallery.html">Gallery</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
    <img src="https://upload.wikimedia.org/wikipedia/commons/3/33/-LOVE-love-36983825-1680-1050.jpg">

</body>

</html>


答:
change your link tag(rel property) to</p>

```<code><link href="style.css" rel="stylesheet" type="text/css">
</code>```

Title: I can't seem to link html to css

Body:
change your link tag(rel property) to

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


问:
javascript - hide / show div based on selection
I have a rails form where user has to select a value from a drop down menu and based on that value, the rest fo the form elements are displayed.

```<code><div id="A">
a
b
c
</div>

<div id="B">
x
y
z
c
</div>

<div id="B">
w
a
q
c
</div>
</code>```

When user selects value A from the select menu, the div with id A is displayed and the rest of the divs are hidden.

The problem is some fields are repeated in the different divs and when user enters a value for field 'a' in div A, this value gets overwritten by the blank value in div B, although div B is hidden from view.

I would like to know whether it's possible to have the same fields in different divs and be able to store the value of the field found in the displayed div only, even if that field is found in other divs.

Many many thanks for any suggestion provided.

答:
Why not give the fields slightly different values, and check which one is actually filled out with an onsubmit function.

You have:

a1
b
c1

x
y
z
c2

w
a1
q
c2

Then in onsubmit:
if(a1 !='') { submit a1}
else if(a2 != '') {submit a2}

Sorry, not exactly code, but it's a place for you to start from.

Body:
I have a rails form where user has to select a value from a drop down menu and based on that value, the rest fo the form elements are displayed.

a
b
c

x
y
z
c

w
a
q
c

When user selects value A from the select menu, the div with id A is displayed and the rest of the divs are hidden.

The problem is some fields are repeated in the different divs and when user enters a value for field 'a' in div A, this value gets overwritten by the blank value in div B, although div B is hidden from view.

I would like to know whether it's possible to have the same fields in different divs and be able to store the value of the field found in the displayed div only, even if that field is found in other divs.

Many many thanks for any suggestion provided.


问:
FCM Web - Same foreground and background notification (reuse background notification in foreground)
I would like to know if it's possible to show the same notification when my website is in foreground, as when it is in background. I don't want to personalize the looks of the notification, I want to reuse it exactly how it is.

Right now, I'm handling the arrival of the notification using this function:

```<code>function messageReceived(payload) {
    // TODO implement actions on message received
    console.log(payload);
}
</code>```

But I don't want to do it. Deleting this function doesn't help.

答:
To work on Android, notifications have to be sent from the serviceWorker.

To get the Firebase serviceWorker registration and use that to show the notification, you can do:

```<code>messaging.onMessage(function(payload) {
    console.log("onMessage: ", payload);
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
        registration.showNotification(
            payload.notification.title,
            payload.notification
        )
    });
});
</code>```

Body:
I would like to know if it's possible to show the same notification when my website is in foreground, as when it is in background. I don't want to personalize the looks of the notification, I want to reuse it exactly how it is.

Right now, I'm handling the arrival of the notification using this function:

function messageReceived(payload) {
    // TODO implement actions on message received
    console.log(payload);
}

But I don't want to do it. Deleting this function doesn't help.

Body:
To work on Android, notifications have to be sent from the serviceWorker.

To get the Firebase serviceWorker registration and use that to show the notification, you can do:

messaging.onMessage(function(payload) {
    console.log("onMessage: ", payload);
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
        registration.showNotification(
            payload.notification.title,
            payload.notification
        )
    });
});


问:
Remove duplicates from the string in CPP
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

```<code>#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}
</code>```

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

答:
So, after doing a bit of reading on the Internet I realized that I was trying to return a pointer to the local array in the removeDuplicates() function.

This is what works fine

```<code>#include <bits/stdc++.h>
using namespace std;
void removeDuplicates(string &s,int n){
    vector<char> vec;
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            vec.push_back(s[i]);
            exists[s[i]]++;
        }
    }
    for(auto x: vec)
        cout << x;
}

//driver code
int main(){
    string str;
    cin >> str;
    removeDuplicates(str,str.length());
    return 0;
}
</code>```

PS: We can make the return type of function to vector as well.

Body:
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

Body:
So, after doing a bit of reading on the Internet I realized that I was trying to return a pointer to the local array in the removeDuplicates() function.

This is what works fine

#include <bits/stdc++.h>
using namespace std;
void removeDuplicates(string &s,int n){
    vector<char> vec;
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            vec.push_back(s[i]);
            exists[s[i]]++;
        }
    }
    for(auto x: vec)
        cout << x;
}

//driver code
int main(){
    string str;
    cin >> str;
    removeDuplicates(str,str.length());
    return 0;
}

PS: We can make the return type of function to vector as well.


问:
Reuse an operator<< for several classes
I have two classes (this is a, extract from my actual more complex case)

```<code>class ClUInt {
public:
    ClUInt() : _i(2), _arr{1,2,3} {};
    ClUInt(const unsigned int ui) : _i(ui) {};
private:
    unsigned int _i;
    double _arr[3];
};

class ClInt {
public:
    ClInt() : _i(-2), _arr{-1,-2,-3} {};
    ClInt(const int i) : ClInt() { _i = i; };
private:
    int _i;
    double _arr[3];
};
</code>```

They are very similar, but one uses int and the other unsigned int for member _i.

I want to overload operator<< with, e.g.,

```<code>std::ostream& operator<<(std::ostream& os, const ClInt & ci)
{
    cout << ci._i << endl;
    cout << ci._arr[0] << endl;
    return os;
}
</code>```

Assume I want the "same" overload for both classes.

How can I write it only once, so it is easier to maintain?
I thought of defining my own cast, but I am not sure it is the way to go...

Notes:

I think I have no chance of making the two classes share any part of an inheritance tree.

They could actually be structs, so if privacy affects the answer, one can assume _i and _arr are public.

In the actual case, the two structs have a larger number of "common" members which are signed/unsigned, respectively.

答:
Use a template with concepts:

```<code>#include <concepts>
#include <iostream>

template<typename T>
concept ClInteger = std::same_as<T, ClInt> || std::same_as<T, ClUInt>;

template <ClInteger T>
std::ostream& operator<<(std::ostream& os, const T & ci)
{
    std::cout << ci._i << '\n';
    std::cout << ci._arr[0] << '\n';
    return os;
}
</code>```

Note that this operator must be the friend of those classes to have access to their private fields.

LIVE

Title: Reuse an operator<< for several classes

Body:
I have two classes (this is a, extract from my actual more complex case)

class ClUInt {
public:
    ClUInt() : _i(2), _arr{1,2,3} {};
    ClUInt(const unsigned int ui) : _i(ui) {};
private:
    unsigned int _i;
    double _arr[3];
};

class ClInt {
public:
    ClInt() : _i(-2), _arr{-1,-2,-3} {};
    ClInt(const int i) : ClInt() { _i = i; };
private:
    int _i;
    double _arr[3];
};

They are very similar, but one uses int and the other unsigned int for member _i.

I want to overload operator<< with, e.g.,

std::ostream& operator<<(std::ostream& os, const ClInt & ci)
{
    cout << ci._i << endl;
    cout << ci._arr[0] << endl;
    return os;
}

Assume I want the "same" overload for both classes.

How can I write it only once, so it is easier to maintain?
I thought of defining my own cast, but I am not sure it is the way to go...

Notes:

I think I have no chance of making the two classes share any part of an inheritance tree.

They could actually be structs, so if privacy affects the answer, one can assume _i and _arr are public.

In the actual case, the two structs have a larger number of "common" members which are signed/unsigned, respectively.

Body:
Use a template with concepts:

#include <concepts>
#include <iostream>

template<typename T>
concept ClInteger = std::same_as<T, ClInt> || std::same_as<T, ClUInt>;

template <ClInteger T>
std::ostream& operator<<(std::ostream& os, const T & ci)
{
    std::cout << ci._i << '\n';
    std::cout << ci._arr[0] << '\n';
    return os;
}

Note that this operator must be the friend of those classes to have access to their private fields.

LIVE


问:
px unit width resolution problem in screen
In this setup

```<code><div class="a">

</div>
</code>```

```<code>.a {
   width: 400px;
   height: 600px;
}

</code>```

if the screen resolution is 1600*1200, will the div's width be 25% of the screen in the browser ?

if the screen resolution is 4000*2400, will the div's width be 10% of the screen in the browser ?

I want to be always 25%.

If I use percent to set the width, div will shrink automatically when browser is not in full screen.

答:
Instead of px or % , the best practice is to Use the following units to make your div or any elements responsive on the basis of screen size as they target the "viewport" .
Viewport Width (vw) Viewport Height (vh) — This unit is based on the height of the viewport. A value of 1vh is equal to 1% of the viewport height. Viewport Width (vw) — This unit is based on the width of the viewport. A value of 1vw is equal to 1% of the viewport width.
for example
  width: 40vw;
  height: 60vh; </p>

<p>This will fix your problem. You can use this unit while defining size of your fonts as well. </p>

Body:
In this setup

.a {
   width: 400px;
   height: 600px;
}

if the screen resolution is 1600*1200, will the div's width be 25% of the screen in the browser ?

if the screen resolution is 4000*2400, will the div's width be 10% of the screen in the browser ?

I want to be always 25%.

If I use percent to set the width, div will shrink automatically when browser is not in full screen.

Body:
Instead of px or % , the best practice is to Use the following units to make your div or any elements responsive on the basis of screen size as they target the "viewport" .
Viewport Width (vw) Viewport Height (vh) — This unit is based on the height of the viewport. A value of 1vh is equal to 1% of the viewport height. Viewport Width (vw) — This unit is based on the width of the viewport. A value of 1vw is equal to 1% of the viewport width.
for example
  width: 40vw;
  height: 60vh;

This will fix your problem. You can use this unit while defining size of your fonts as well.


答:
Make sure your style.css is in the same folder as your HTML file.

since you are using directly the filename as path.

Title: I can't seem to link html to css

Body:
    <!DOCTYPE html>

    <link href="style.css" rel="designpage" type="text/css">
    <title> Viktoria Niemann </title>

Dear Vik

Home

About

Gallery

Contact

I am not sure why html is not linking to css. I think i have written a code correctly


问:
How to use a conditional statement with regex in PowerShell?
There are about ten lines of data.  For each line of data I want to indicate whether that line contains numerals.

How can I print out "yes, this line has numerals" or "no, this line has no numerals" for each and every line, exactly once?

output:

```<code>thufir@dur:~/flwor/csv$
thufir@dur:~/flwor/csv$ pwsh import.ps1
no digits

Name
----
people…

thufir@dur:~/flwor/csv$
</code>```

code:

```<code>$text = Get-Content -Raw ./people.csv
[array]::Reverse($text)

$tempAttributes = @()
$collectionOfPeople = @()

ForEach ($line in $text) {
  if($line -notmatch '.*?[0-9].*?') {
    $tempAttributes += $line
    Write-Host "matches digits"
  }
  else {
    Write-Host "no digits"
    $newPerson = [PSCustomObject]@{
      Name       = $line
      Attributes = $tempAttributes
    }
    $tempAttributes = @()
    $collectionOfPeople += $newPerson
  }
}

$collectionOfPeople
</code>```

data:

```<code>people
joe
phone1
phone2
phone3
sue
cell4
home5
alice
atrib6
x7
y9
z10
</code>```

The only reason I'm printing "digits" or "no digits" is as a marker to aid in building the object.

答:
You can use the following:

```<code>switch -regex -file people.csv {
    '\d' { "yes" ; $_ }
    default { "no"; $_ }
}
</code>```

\d is a regex character matching a digit. A switch statement with -regex allows for regex expressions to be used for matching text. The default condition is picked when no other condition is met. $_ is the current line being processed.

switch is generally faster than Get-Content for line by line processing. Since you do want to perform certain actions per line, you likely don’t want to use the -Raw parameter because that will read in all file contents as one single string.

```<code># For Reverse Output
$output = switch -regex -file people.csv {
    '\d' { "yes" ; $_ }
    default { "no"; $_ }
}
$output[($output.GetUpperBound(0))..0)]
</code>```

Body:
There are about ten lines of data.  For each line of data I want to indicate whether that line contains numerals.

How can I print out "yes, this line has numerals" or "no, this line has no numerals" for each and every line, exactly once?

output:

thufir@dur:~/flwor/csv$
thufir@dur:~/flwor/csv$ pwsh import.ps1
no digits

Name
----
people…

thufir@dur:~/flwor/csv$

code:

$text = Get-Content -Raw ./people.csv
[array]::Reverse($text)

$tempAttributes = @()
$collectionOfPeople = @()

ForEach ($line in $text) {
  if($line -notmatch '.*?[0-9].*?') {
    $tempAttributes += $line
    Write-Host "matches digits"
  }
  else {
    Write-Host "no digits"
    $newPerson = [PSCustomObject]@{
      Name       = $line
      Attributes = $tempAttributes
    }
    $tempAttributes = @()
    $collectionOfPeople += $newPerson
  }
}

$collectionOfPeople

data:

people
joe
phone1
phone2
phone3
sue
cell4
home5
alice
atrib6
x7
y9
z10

The only reason I'm printing "digits" or "no digits" is as a marker to aid in building the object.

Body:
You can use the following:

switch -regex -file people.csv {
    '\d' { "yes" ; $_ }
    default { "no"; $_ }
}

\d is a regex character matching a digit. A switch statement with -regex allows for regex expressions to be used for matching text. The default condition is picked when no other condition is met. $_ is the current line being processed.

switch is generally faster than Get-Content for line by line processing. Since you do want to perform certain actions per line, you likely don’t want to use the -Raw parameter because that will read in all file contents as one single string.

# For Reverse Output
$output = switch -regex -file people.csv {
    '\d' { "yes" ; $_ }
    default { "no"; $_ }
}
$output[($output.GetUpperBound(0))..0)]


答:
Maybe it's just coincidence, but your two classes share a lot. So, why not turn them into templates:</p>

```<code>template<typename integer_type>
class IntegerClass
{
    /// ... further code elided

    friend ostream& operator<<(ostream& out, IntegerClass const& obj)
    {
        return out
            << obj._i << endl
            << obj._arr[0] << endl;
    }
    integer_type _i;
    double _arr[3];
};

// optional typedefs
// These are a matter of taste, not actually mine.
typedef IntegerClass<unsigned int> ClUInt;
typedef IntegerClass<signed int> ClInt;
</code>```

Title: Reuse an operator<< for several classes

Body:
Maybe it's just coincidence, but your two classes share a lot. So, why not turn them into templates:

template<typename integer_type>
class IntegerClass
{
    /// ... further code elided

    friend ostream& operator<<(ostream& out, IntegerClass const& obj)
    {
        return out
            << obj._i << endl
            << obj._arr[0] << endl;
    }
    integer_type _i;
    double _arr[3];
};

// optional typedefs
// These are a matter of taste, not actually mine.
typedef IntegerClass<unsigned int> ClUInt;
typedef IntegerClass<signed int> ClInt;


问:
How to keep XML in URLs from being interpreted?
I'm trying to get PHP to echo this:

```<code>http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<TrackRequest USERID=\"123456\"><TrackID ID=".$trackno."></TrackID></TrackRequest>";
</code>```

However, when I open this page in my browser (FF4), only this shows up:

```<code>http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=
</code>```

The browser thinks that  onwards is part of a XML document so it does not render it, as shown here:

(parts blanked out for obvious reasons :D)

How do I fix this issue?

Thanks!

答:
You can do this:

```<code>$a = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<TrackRequest USERID=\"123456\"><TrackID ID=".$trackno."></TrackID></TrackRequest>";
echo htmlentities($a);
</code>```

or

```<code>echo "```$a```"; // the first is better;
</code>```

Body:
I'm trying to get PHP to echo this:

http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<TrackRequest USERID=\"123456\"><TrackID ID=".$trackno."></TrackID></TrackRequest>";

However, when I open this page in my browser (FF4), only this shows up:

http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=

The browser thinks that  onwards is part of a XML document so it does not render it, as shown here:

(parts blanked out for obvious reasons :D)

How do I fix this issue?

Thanks!

Body:
You can do this:

$a = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<TrackRequest USERID=\"123456\"><TrackID ID=".$trackno."></TrackID></TrackRequest>";
echo htmlentities($a);

or

echo "<pre>$a</pre>"; // the first is better;


问:
CMake Error at FindPackageHandleStandardArgs.cmake:137 (message): Could NOT find Boost (missing: regex) (found suitable version "1.72.0",
I downloaded the boost_1_72_0.tar.gz from the official site and unzipped it into my downloads folder at /USERS/macuser/Downloads/boost_1_72_0

I keep getting the following error when trying to link a simple .cpp file with Boost::regex

```<code>-- The C compiler identification is AppleClang 11.0.0.11000033
-- The CXX compiler identification is AppleClang 11.0.0.11000033
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Warning at /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:1144 (message):
  New Boost version may have incorrect or missing dependencies and imported
  targets
Call Stack (most recent call first):
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:1266 (_Boost_COMPONENT_DEPENDENCIES)
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:1904 (_Boost_MISSING_DEPENDENCIES)
  examples/HelloBoost/CMakeLists.txt:27 (find_package)

CMake Error at /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
  Could NOT find Boost (missing: regex) (found suitable version "1.72.0",
  minimum required is "1.72.0")
Call Stack (most recent call first):
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:2161 (find_package_handle_standard_args)
  examples/HelloBoost/CMakeLists.txt:27 (find_package)
</code>```

My CMakeLists.txt file looks like below:

```<code>cmake_minimum_required(VERSION 3.1)

set (CMAKE_CXX_STANDARD 11)
set (PROJECT "Hello-Boost")

# headers
include_directories(include)

# sources
file(GLOB SOURCES "src/*.cpp")

# BOOST Configuration

set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

set(Boost_INCLUDE_DIR /USERS/macuser/Downloads/boost_1_72_0/boost)
set(Boost_LIBRARY_DIR /USERS/macuser/Downloads/boost_1_72_0/libs)

find_package(Boost 1.72.0 COMPONENTS regex REQUIRED)

if(Boost_FOUND)
    message("boost lib: ${Boost_LIBRARIES}")
    message("boost inc:${Boost_INCLUDE_DIR}")
emdif()

include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

# executable target
add_executable(${PROJECT} ${SOURCES})

# link boost
target_link_libraries(${PROJECT} PUBLIC Boost::regex)
</code>```

My question is simple:

What in God's name is going wrong with the Cmake?
Why on Earth it cannot find the darn boost library when millions of other human beings  have successfully done so?

Thankyou

答:
Before using Boost::regex you need to built Boost because it is not a header only library (as the majority of the other Boost libraries). This is usually done during installation via a package manager like homebrew or macports.

Header only libraries do not need to be added to the COMPONENTS section of your find_package call.

Then you do a

```<code>find_package(BOOST 1.72.0 COMPONENTS regex REQUIRED)
</code>```

as you already did and later add the libraries to your target either by

```<code>target_link_libraries(${PROJECT} PUBLIC Boost::regex)
</code>```

If you intend to use other Boost libraries later (header only or not), you should either name them explicitly in the target_link_libraries call or add

```<code>target_link_libraries(${PROJECT} PUBLIC ${Boost_LIBRARIES})
</code>```

This will also add the Boost directory to your include directories.
You can then omit the following lines

```<code>include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})
</code>```

If you'd rather like to use the static libraries instead of the dynamic ones use

```<code>set(Boost_USE_STATIC_LIBS ON)
</code>```

before your find_package call.

Body:
I downloaded the boost_1_72_0.tar.gz from the official site and unzipped it into my downloads folder at /USERS/macuser/Downloads/boost_1_72_0

I keep getting the following error when trying to link a simple .cpp file with Boost::regex

-- The C compiler identification is AppleClang 11.0.0.11000033
-- The CXX compiler identification is AppleClang 11.0.0.11000033
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Warning at /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:1144 (message):
  New Boost version may have incorrect or missing dependencies and imported
  targets
Call Stack (most recent call first):
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:1266 (_Boost_COMPONENT_DEPENDENCIES)
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:1904 (_Boost_MISSING_DEPENDENCIES)
  examples/HelloBoost/CMakeLists.txt:27 (find_package)

CMake Error at /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
  Could NOT find Boost (missing: regex) (found suitable version "1.72.0",
  minimum required is "1.72.0")
Call Stack (most recent call first):
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
  /usr/local/Cellar/cmake/3.15.4/share/cmake/Modules/FindBoost.cmake:2161 (find_package_handle_standard_args)
  examples/HelloBoost/CMakeLists.txt:27 (find_package)

My CMakeLists.txt file looks like below:

cmake_minimum_required(VERSION 3.1)

set (CMAKE_CXX_STANDARD 11)
set (PROJECT "Hello-Boost")

# headers
include_directories(include)

# sources
file(GLOB SOURCES "src/*.cpp")

# BOOST Configuration

set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

set(Boost_INCLUDE_DIR /USERS/macuser/Downloads/boost_1_72_0/boost)
set(Boost_LIBRARY_DIR /USERS/macuser/Downloads/boost_1_72_0/libs)

find_package(Boost 1.72.0 COMPONENTS regex REQUIRED)

if(Boost_FOUND)
    message("boost lib: ${Boost_LIBRARIES}")
    message("boost inc:${Boost_INCLUDE_DIR}")
emdif()

include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

# executable target
add_executable(${PROJECT} ${SOURCES})

# link boost
target_link_libraries(${PROJECT} PUBLIC Boost::regex)

My question is simple:

What in God's name is going wrong with the Cmake?
Why on Earth it cannot find the darn boost library when millions of other human beings  have successfully done so?

Thankyou

Body:
Before using Boost::regex you need to built Boost because it is not a header only library (as the majority of the other Boost libraries). This is usually done during installation via a package manager like homebrew or macports.

Header only libraries do not need to be added to the COMPONENTS section of your find_package call.

Then you do a

find_package(BOOST 1.72.0 COMPONENTS regex REQUIRED)

as you already did and later add the libraries to your target either by

target_link_libraries(${PROJECT} PUBLIC Boost::regex)

If you intend to use other Boost libraries later (header only or not), you should either name them explicitly in the target_link_libraries call or add

target_link_libraries(${PROJECT} PUBLIC ${Boost_LIBRARIES})

This will also add the Boost directory to your include directories.
You can then omit the following lines

include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

If you'd rather like to use the static libraries instead of the dynamic ones use

set(Boost_USE_STATIC_LIBS ON)

before your find_package call.


问:
Laravel ajax file upload (excel file: 1M+ rows)
I'm trying to create a proper progress bar for my excel file upload in Laravel
I'm using ajax to upload the file and have gotten the progress bar for the upload part to "kind off" work. My only problem, is that when the file is uploaded (100% complete on the upload part) it still says "uploading...". It looks like uploadProgress is not jumping forward to success when it's done.

The file is processed in the back by laravel-excel, and it takes a very very long time to process big excel files with 1M+ rows.

Here is also a screenshot of it. I console logged the progress and it all went fine until it should go over to the success function in the ajax call.

What could I do to fix this? To limit the amount of rows in the excel file uploads are not something I can do as the website I'm creating has the need to upload files that has this many or more rows.

Also, my code for the ajax upload:

```<code>    // AJAX form upload
    var form = $('.form-import');
    var bar = $('.import-progress-bar');
    var status = $('.import-status');

    form.ajaxForm({
        beforeSend: function() {
            status.empty();
            bar.attr('value', 0);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            bar.attr('value', percentComplete);
            status.html('Uploading...');
            console.log('Upload progress - '+ percentComplete + '%');
        },
        success: function() {
            status.html('Importing rows...');
        },
        complete: function() {
            status.html('Importing complete!');
        }
    });
</code>```

答:
I would use mysql LOAD DATA INTO, to process the excell (csv) file into database. I had a similar task, with several 5-600 MB csv files, which generated php runtime errors.

With the LOAD DATA INTO, I have imported these files in seconds, without issues.

Read more:

https://dev.mysql.com/doc/refman/8.0/en/load-data.html

Body:
I'm trying to create a proper progress bar for my excel file upload in Laravel
I'm using ajax to upload the file and have gotten the progress bar for the upload part to "kind off" work. My only problem, is that when the file is uploaded (100% complete on the upload part) it still says "uploading...". It looks like uploadProgress is not jumping forward to success when it's done.

The file is processed in the back by laravel-excel, and it takes a very very long time to process big excel files with 1M+ rows.

Here is also a screenshot of it. I console logged the progress and it all went fine until it should go over to the success function in the ajax call.

What could I do to fix this? To limit the amount of rows in the excel file uploads are not something I can do as the website I'm creating has the need to upload files that has this many or more rows.

Also, my code for the ajax upload:

    // AJAX form upload
    var form = $('.form-import');
    var bar = $('.import-progress-bar');
    var status = $('.import-status');

    form.ajaxForm({
        beforeSend: function() {
            status.empty();
            bar.attr('value', 0);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            bar.attr('value', percentComplete);
            status.html('Uploading...');
            console.log('Upload progress - '+ percentComplete + '%');
        },
        success: function() {
            status.html('Importing rows...');
        },
        complete: function() {
            status.html('Importing complete!');
        }
    });


问:
can ::before pseudo element be a link?
I am trying to add metadata to html, and show link from ::before {} element.

    lorem

        ipsum

```

<pre class="lang-css prettyprint-override"><code>[data-discussion]:hover::before{
    background: pink;
    content: attr(data-discussion);
    /* link be here! */
}
</code>```

The ::before attribute is really convenient, as I am able to apply it to the whole page without rewriting my html.
Is there a way to add href-like link to it?

答: No, that is not possible with just CSS, you would have to generate a tags , for example with JavaScript.

Title: can ::before pseudo element be a link?

Body:
I am trying to add metadata to html, and show link from ::before {} element.

    lorem

        ipsum

[data-discussion]:hover::before{
    background: pink;
    content: attr(data-discussion);
    /* link be here! */
}

The ::before attribute is really convenient, as I am able to apply it to the whole page without rewriting my html.
Is there a way to add href-like link to it?


问:
Ranking newer items fairly?
Using StackOverflow itself as an example, if you had any such system where entries were voted and viewed in order of rank based on this, how do you compensate to sort newer entries fairly? That is, if ten bad answers are given and upvoted, how do you make sure people see the new entry that might be better, but hasn't had time to gather votes or even been seen all the way at the bottom?</p>

答:
You could add 10 "virtual upvotes" to a new post, that decay with time or view.

For example you could reduce the virtual upvotes by 1 for every hour the answer is there or for every 100 views of the answer (assuming that if 100 people saw the post and didn't bother voting on it, it is probably correctly valued with 0 real votes.

Since screens get bigger and wider allthe time, you also could list all answers twice, on the left sorted by rank, on the right sorted by age.

OwnerDisplayName: ironfroggy

Title: Ranking newer items fairly?

LastEditorDisplayName: Pete Kirkham

OwnerDisplayName: Jens Schauder


问:
Create Firebase notification with page in foreground/focus
With Firebase Cloud Messaging (for web), how can I generate the notification that appears when the webpage is closed or in the background, but when I'm actually focused on the webpage?

It's my understanding that messaging.onMessage(...) is where I handle incoming messages when the page is in focus, but I can't seem to find documentation on how I could still create the notification pop-ups as though the page were in the background.

Thanks for your time!

答:
Since Notification is deprecated in Android, you should use Firebase serviceWorker registration to show the notification.

As of Feb 2020, it looks like Firebase registers its serviceWorker with the '/firebase-cloud-messaging-push-scope' scope (as can be seen in chrome devtools -> Application -> Service Workers)

To use that, you can do:

```<code>messaging.onMessage(function(payload) {
    console.log("onMessage: ", payload);
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
        registration.showNotification(
            payload.notification.title,
            payload.notification
        )
    });
});
</code>```

Body:
Since Notification is deprecated in Android, you should use Firebase serviceWorker registration to show the notification.

As of Feb 2020, it looks like Firebase registers its serviceWorker with the '/firebase-cloud-messaging-push-scope' scope (as can be seen in chrome devtools -> Application -> Service Workers)

To use that, you can do:

messaging.onMessage(function(payload) {
    console.log("onMessage: ", payload);
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
        registration.showNotification(
            payload.notification.title,
            payload.notification
        )
    });
});


问:
Scroll view not scrolling in storyboard
I have the following scroll view although when I run the simulator I am not able to scroll. I have vertical constraints set for the content items, any idea why this is?

答: can you provide your constraint details? i hope you have added one view on top of the scrollview.</p>

Title: Scroll view not scrolling in storyboard


问:
Why my ViewModel is still alive after I replaced current fragment in Android?
Example, If I replaced 'fragmentA' with 'fragmentB', the 'viewModelA' of fragmentA is still live. why ?

onCreate() of Fragment

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    viewModel = ViewModelProvider.NewInstanceFactory().create(InvoicesViewModel::class.java)
}
</code>```

ViewModel

```<code>class InvoicesViewModel : ViewModel() {

init {
    getInvoices()
}

private fun getInvoices() {

    viewModelScope.launch {

        val response = safeApiCall() {
            // Call API here
        }

        while (true) {
            delay(1000)
            println("Still printing although the fragment of this viewModel destroied")
        }

        if (response is ResultWrapper.Success) {
            // Do work here
        }
    }
}
}
</code>```

This method used to replace fragment

```<code>fun replaceFragment(activity: Context, fragment: Fragment, TAG: String) {
    val myContext = activity as AppCompatActivity
    val transaction = myContext.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.content_frame, fragment, TAG)
    transaction.commitNow()
}
</code>```

You will note the while loop inside the Coroutine still work although after replace fragment to another fragment.

答: Check, if you have created the ViewModel in Activity passing the context of activity or fragment.</p>

Body:
Example, If I replaced 'fragmentA' with 'fragmentB', the 'viewModelA' of fragmentA is still live. why ?

onCreate() of Fragment

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    viewModel = ViewModelProvider.NewInstanceFactory().create(InvoicesViewModel::class.java)
}

ViewModel

class InvoicesViewModel : ViewModel() {

init {
    getInvoices()
}

private fun getInvoices() {

    viewModelScope.launch {

        val response = safeApiCall() {
            // Call API here
        }

        while (true) {
            delay(1000)
            println("Still printing although the fragment of this viewModel destroied")
        }

        if (response is ResultWrapper.Success) {
            // Do work here
        }
    }
}
}

This method used to replace fragment

fun replaceFragment(activity: Context, fragment: Fragment, TAG: String) {
    val myContext = activity as AppCompatActivity
    val transaction = myContext.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.content_frame, fragment, TAG)
    transaction.commitNow()
}

You will note the while loop inside the Coroutine still work although after replace fragment to another fragment.


问:
Java String declaration
What is the difference between String str = new String("SOME") and String str="SOME"
Does these declarations gives performance variation.

答:
```<code>String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable
</code>```

Title: Java String declaration