问:
How to copy range links to addin worksheet and then create a named range from it?
Is it possible to link selected range (copy with links?) to addin worksheet, then create a named range in that addin workbook and then finally create a named range, which refers to that named range stored in addin?

For example, I have this data:

I am trying to copy it with links to the addin worksheet. Addin is called "addin_test.xlam" and the worksheet stored in it is called "ws_test". I have this piece of code:

```<code>Dim rng As Range
Set rng = Selection
rng.Copy
ThisWorkbook.Sheets("ws_test").Range("A1").PasteSpecial
</code>```

(How to copy links, instead of absolute values? I would like my addin sheet update its data according to activesheet values)

Then I create a named range in my addin workbook:

```<code>ThisWorkbook.Names.Add Name:="Test_addin_name", RefersTo:=ThisWorkbook.Sheets("ws_test").Range("A1:A3")
</code>```

Lastly, I am looking for a way to create a named range in activesheet (open workbook) and link it to the named range in my add-in. This is what I have so far:

```<code>ActiveSheet.Names.Add Name:="Test_sheet_name", RefersTo:=ThisWorkbook.Name & "!" & ThisWorkbook.Names("Test_addin_name").Name
</code>```

Named range is created correctly but sadly it returns "string" value of what I typed after RefersTo parameter. Value of this named range is not {100,200,300} but "WorkbookName...". I have tried different things but nothing seems to be working.

Can somebody help me?

答:
Change, please changing

```<code>RefersTo:=ThisWorkbook.Name & "!" & ThisWorkbook.Names("Test_addin_name").Name
</code>```

with

```<code> "[" & ThisWorkbook.Name & "]ws_test!" & ThisWorkbook.Names("Test_addin_name").RefersTo
</code>```

Related to linking solution, please try the next code. It writes a formula in the range you want being updated when the add-in Name is changed:

```<code>Sub LinkAddinName()
   Dim sh As Worksheet
   Set sh = ActiveSheet
   sh.Range("A1").Formula = "=COUNTA('" & ThisWorkbook.Name & "'!Test_addin_name)"
End Sub
</code>```

Instead of CountA you can use any formula using the range. If you need to have a similar range, you must write formulas for each cell to be linked to the correspondent cell of the named range:

```<code>Sub LinkAddinNameEachCell()
   Dim sh As Worksheet, cel As Range
   Set sh = ActiveSheet

   For Each cel In ThisWorkbook.Names("Test_addin_name").RefersToRange
        sh.Range(cel.address).Formula = "='[" & ThisWorkbook.Name & "]ws_test'!" & cel.address
   Next
End Sub
</code>```

Body:
Is it possible to link selected range (copy with links?) to addin worksheet, then create a named range in that addin workbook and then finally create a named range, which refers to that named range stored in addin?

For example, I have this data:

I am trying to copy it with links to the addin worksheet. Addin is called "addin_test.xlam" and the worksheet stored in it is called "ws_test". I have this piece of code:

Dim rng As Range
Set rng = Selection
rng.Copy
ThisWorkbook.Sheets("ws_test").Range("A1").PasteSpecial

(How to copy links, instead of absolute values? I would like my addin sheet update its data according to activesheet values)

Then I create a named range in my addin workbook:

ThisWorkbook.Names.Add Name:="Test_addin_name", RefersTo:=ThisWorkbook.Sheets("ws_test").Range("A1:A3")

Lastly, I am looking for a way to create a named range in activesheet (open workbook) and link it to the named range in my add-in. This is what I have so far:

ActiveSheet.Names.Add Name:="Test_sheet_name", RefersTo:=ThisWorkbook.Name & "!" & ThisWorkbook.Names("Test_addin_name").Name

Named range is created correctly but sadly it returns "string" value of what I typed after RefersTo parameter. Value of this named range is not {100,200,300} but "WorkbookName...". I have tried different things but nothing seems to be working.

Can somebody help me?

Body:
Change, please changing

RefersTo:=ThisWorkbook.Name & "!" & ThisWorkbook.Names("Test_addin_name").Name

with

 "[" & ThisWorkbook.Name & "]ws_test!" & ThisWorkbook.Names("Test_addin_name").RefersTo

Related to linking solution, please try the next code. It writes a formula in the range you want being updated when the add-in Name is changed:

Sub LinkAddinName()
   Dim sh As Worksheet
   Set sh = ActiveSheet
   sh.Range("A1").Formula = "=COUNTA('" & ThisWorkbook.Name & "'!Test_addin_name)"
End Sub

Instead of CountA you can use any formula using the range. If you need to have a similar range, you must write formulas for each cell to be linked to the correspondent cell of the named range:

Sub LinkAddinNameEachCell()
   Dim sh As Worksheet, cel As Range
   Set sh = ActiveSheet

   For Each cel In ThisWorkbook.Names("Test_addin_name").RefersToRange
        sh.Range(cel.address).Formula = "='[" & ThisWorkbook.Name & "]ws_test'!" & cel.address
   Next
End Sub


来源: stackexchange

问:
Border around my page is stopping element hover from working
I have a border around my web page which is preventing from hovers over element from working.
In the example below the green box is to scale when hovered over but doesn't.

If I add a negative z-index to body::before tag it works. But then all text goes over the border when the page is scrolled.

I need the border to always be on top and the hovers to still work.

.zoom {
  padding: 50px;
  background-color: green;
  transition: transform .2s;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

.zoom:hover {
  -ms-transform: scale(1.5);
  /* IE 9 */
  -webkit-transform: scale(1.5);
  /* Safari 3-8 */
  transform: scale(1.5);
}

.lorem {
  width: 300px;
  margin: auto;
}

body::before {
  content: '';
  position: fixed;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  border: 15px solid #30582b;
  padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="zoom"></div>
<div class="lorem">

  What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen
  book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to
  make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type
  and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer
  took a galley of type and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when
  an unknown printer took a galley of type and scrambled it to make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever
  since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has?

</div></code>```

答:
Set pointer-events: none on the border's pseudo-element:

.zoom {
  padding: 50px;
  background-color: green;
  transition: transform .2s;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

.zoom:hover {
  -ms-transform: scale(1.5);
  /* IE 9 */
  -webkit-transform: scale(1.5);
  /* Safari 3-8 */
  transform: scale(1.5);
}

.lorem {
  width: 300px;
  margin: auto;
}

body::before {
  content: '';
  position: fixed;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  border: 15px solid #30582b;
  padding: 0px;
  pointer-events: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="zoom"></div>
<div class="lorem">

  What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen
  book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to
  make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type
  and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer
  took a galley of type and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when
  an unknown printer took a galley of type and scrambled it to make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever
  since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has?

</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a border around my web page which is preventing from hovers over element from working.
In the example below the green box is to scale when hovered over but doesn't.

If I add a negative z-index to body::before tag it works. But then all text goes over the border when the page is scrolled.

I need the border to always be on top and the hovers to still work.

.zoom {
  padding: 50px;
  background-color: green;
  transition: transform .2s;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

.zoom:hover {
  -ms-transform: scale(1.5);
  /* IE 9 */
  -webkit-transform: scale(1.5);
  /* Safari 3-8 */
  transform: scale(1.5);
}

.lorem {
  width: 300px;
  margin: auto;
}

body::before {
  content: '';
  position: fixed;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  border: 15px solid #30582b;
  padding: 0px;
}

  What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen
  book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to
  make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type
  and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer
  took a galley of type and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when
  an unknown printer took a galley of type and scrambled it to make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever
  since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has?

Body:
Set pointer-events: none on the border's pseudo-element:

.zoom {
  padding: 50px;
  background-color: green;
  transition: transform .2s;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

.zoom:hover {
  -ms-transform: scale(1.5);
  /* IE 9 */
  -webkit-transform: scale(1.5);
  /* Safari 3-8 */
  transform: scale(1.5);
}

.lorem {
  width: 300px;
  margin: auto;
}

body::before {
  content: '';
  position: fixed;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  border: 15px solid #30582b;
  padding: 0px;
  pointer-events: none;
}

<div class="zoom"></div>
<div class="lorem">

  What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen
  book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to
  make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type
  and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer
  took a galley of type and scrambled it to make a type specimen book it has? What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when
  an unknown printer took a galley of type and scrambled it to make a type specimen book it has?What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever
  since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has?

</div>


问:
Unity "The associated script can not be loaded" and "Win32Exception: The system cannot find the file specified"
so I'm new to Unity and I've been trying to test the scene with the script attatched to a character. However, it keeps saying "The associated script cannot be loaded. Please fix any compile errors and assign a valid script." It also says that the name of the file could be different from the name in the code but it isnt, and also it says that the code could be missing MonoBehaviour Scripts. It wont even allow me to attach the script to characters because it cant find the script class.

I've copied and downloaded character movement codes from the internet but they didnt work either. I've also tried deleting and re-making the CS files but that didnt work either. Even adding empty scripts to characters didnt work unless i do it from "Add component"

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    SpriteRenderer sprite;
    Rigidbody2D rigid;

    // Start is called before the first frame update
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        rigid = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        if (Input.GetKey("d"))
            rigid.velocity = new Vector2(2, 0);
        else if (Input.GetKey("a"))
            rigid.velocity = new Vector2(-2, 0);
    }
}
</code>```

There are also these errors in Unity if that helps

答: I think your class name is different from file name.</p>

Body:
so I'm new to Unity and I've been trying to test the scene with the script attatched to a character. However, it keeps saying "The associated script cannot be loaded. Please fix any compile errors and assign a valid script." It also says that the name of the file could be different from the name in the code but it isnt, and also it says that the code could be missing MonoBehaviour Scripts. It wont even allow me to attach the script to characters because it cant find the script class.

I've copied and downloaded character movement codes from the internet but they didnt work either. I've also tried deleting and re-making the CS files but that didnt work either. Even adding empty scripts to characters didnt work unless i do it from "Add component"

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    SpriteRenderer sprite;
    Rigidbody2D rigid;

    // Start is called before the first frame update
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        rigid = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        if (Input.GetKey("d"))
            rigid.velocity = new Vector2(2, 0);
        else if (Input.GetKey("a"))
            rigid.velocity = new Vector2(-2, 0);
    }
}

There are also these errors in Unity if that helps


问:
SetInterval messages not changing
I'm making a loading screen for a game I'm creating with html and JS.  I want various messages to display, about every three seconds.  The SetInterval function doesn't seem to be rotating the messages, even though it works with something else (like an alert every three seconds).  here's the code I've written for the changing messages.</p>

```<code><!doctype html>
<html>
<head><title>Loading screen</title></head>
<script>
let messageNum = 1;

setInterval(function(){
  messageNum++
 }, 1000);

if (messageNum >3) {
  messageNum = 1;
}

if (messageNum === 1) {
  document.write('Message number ONE');
}

if (messageNum === 2) {
  document.write('Message number TWO');
}

if (messageNum === 3) {
  document.write('Message number THREE');
}
</script>
</html>
</code>```

答:
setInterval will run the function I'm your first argument every x ms (second argument).

Since your function only increment the variable, you won't see the message.

The message printing and if statements are not part of that function that run inside the setInterval which make those lines to run only once.

You need to put the 'if' statements and message printing inside the function triggered in setInterval.

P.S.

Please make sure you are using document.write only for testing or streaming. It is not a good practice to use it inside a function, since it will overwrite the existing HTML each time write is called.

Title: SetInterval messages not changing

Body:
I'm making a loading screen for a game I'm creating with html and JS.  I want various messages to display, about every three seconds.  The SetInterval function doesn't seem to be rotating the messages, even though it works with something else (like an alert every three seconds).  here's the code I've written for the changing messages.

<!doctype html>

<title>Loading screen</title>


问:
How to identify an object and make a relationship among them [c#]
What is the best way to identify the objects and their Relationship between them ?
As i am new to Programming[c# windows application],I am finding difficult in making relationship between objects .
Can anyone suggest me the best way to start with?

Thanks,
Karthik

答:
You should probably read up on object oriented programming and design. Then read up on C# programming.

Here are a few book suggestions:

Head First Object Oriented Analysis and Design

Beginning C# 3.0: An Introduction to Object Oriented Programming

Then when you're ready, you can move on to Jon Skeet's book =)

If you're not looking to purchase a book, maybe take a look at this site. It covers key object oriented design principles.

ContentLicense: CC BY-SA 3.0


问:
Select data from one dataframe by comparing against another dataframe in R
Basically I have two datasets, one is on the firm level and one is on the industry level.

The values below are contained the both datasets, although may not be in the same order. The row numbers are different as well.

date <- c(1999,2000,2001...2019)
industry <- c("communication services", "utilities", "financials")

dffirm <- c(firmID, date, industry, beta, asset_ratios)
dfindustry <- c(industry, date, mean_beta, mean_asset_ratios)
```

<p>What I want to do is to compare beta and asset ratios between the two datasets with corresponding industry and year so I can create a portfolio of firms based on certain criteria, such as:</p>

<pre class="lang-r prettyprint-override"><code>dffirm$beta < dfind$beta & dffirm$asset_ratio > dfindustry$mean_asset_ratio
</code>```

答:
Based on your comments, I think you are looking for basic summary statistics for each of the data frames to compare. I think using tidyverse packages could be helpful.

EDITED

```<code>install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")

#some sample datasets
firm_data <- data.frame("date" = c(rep(2009,4),rep(2010,4),rep(2011,4)),
                 "firm_beta" = rnorm(12))

industry_data <- data.frame("date" = c(rep(2009,4),rep(2010,4),rep(2011,4)),
                 "industry" = rep(c("industry1","indsutry2"),6),
                 "industry_beta" = rnorm(12))

#caculate mean for column "beta" in data frame 1
industry_data2 <- industry_data %>% group_by(date) %>%
     summarise(industry_mean_beta = mean(industry_beta))
industry_data2

#caculate mean for column "beta" in data frame 2
firm_data2 <- firm_data %>% group_by(date) %>% summarise(firm_mean_beta = mean(firm_beta))
firm_data2

dc3 <- industry_data2 %>% left_join(firm_data2) %>%
            mutate(beta_differ = case_when(
                  industry_mean_beta > firm_mean_beta ~ "industry > firm",
                  industry_mean_beta < firm_mean_beta ~ "industry > firm",
                  industry_mean_beta == firm_mean_beta ~ "industry > firm"
            ))
</code>```

Body:
Basically I have two datasets, one is on the firm level and one is on the industry level.

The values below are contained the both datasets, although may not be in the same order. The row numbers are different as well.

date <- c(1999,2000,2001...2019)
industry <- c("communication services", "utilities", "financials")

dffirm <- c(firmID, date, industry, beta, asset_ratios)
dfindustry <- c(industry, date, mean_beta, mean_asset_ratios)

What I want to do is to compare beta and asset ratios between the two datasets with corresponding industry and year so I can create a portfolio of firms based on certain criteria, such as:

dffirm$beta < dfind$beta & dffirm$asset_ratio > dfindustry$mean_asset_ratio

Body:
Based on your comments, I think you are looking for basic summary statistics for each of the data frames to compare. I think using tidyverse packages could be helpful.

EDITED

install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")

#some sample datasets
firm_data <- data.frame("date" = c(rep(2009,4),rep(2010,4),rep(2011,4)),
                 "firm_beta" = rnorm(12))

industry_data <- data.frame("date" = c(rep(2009,4),rep(2010,4),rep(2011,4)),
                 "industry" = rep(c("industry1","indsutry2"),6),
                 "industry_beta" = rnorm(12))

#caculate mean for column "beta" in data frame 1
industry_data2 <- industry_data %>% group_by(date) %>%
     summarise(industry_mean_beta = mean(industry_beta))
industry_data2

#caculate mean for column "beta" in data frame 2
firm_data2 <- firm_data %>% group_by(date) %>% summarise(firm_mean_beta = mean(firm_beta))
firm_data2

dc3 <- industry_data2 %>% left_join(firm_data2) %>%
            mutate(beta_differ = case_when(
                  industry_mean_beta > firm_mean_beta ~ "industry > firm",
                  industry_mean_beta < firm_mean_beta ~ "industry > firm",
                  industry_mean_beta == firm_mean_beta ~ "industry > firm"
            ))


问:
Can Laravel 5 handle 1000 concurrent users without lagging badly?
I wanted to know that if 1000 users are concurrently using a website built with laravel 5 and also querying database regularly then how does laravel 5 perform ?
I know it would be slow but will it be highly slow that it would be unbearable ?
Note that i am also going to use ajax a lot.

And lets assume i am using digital ocean cloud service with following configurations

```<code>2GB memory
2 vCPU
40GB SSD
</code>```

I don't expect completely real figures as it is impossible to do so but at least provide some details whether i should go with laravel with some considerable performance.

Please also provide some some tools through which i can check the speed of my laravel 5 application as well as how it will perform when there is actual load as well as other tools through which i can test speed and performance.

And it would be great if someone has real experience of using laravel especially Laravel 5.

And what about Lumen does that really make application faster than laravel and how much ?

答:
I'll try to answer this based on my experience as a software developer. To be honest I definitely will ask for an upgrade whenever it hits 1000 concurrent users at the same time because I won't take a risk with server failure nor data failure.

But let's break it how to engineer this.

It could handle those users if the data fetched is not complex and there are not many operations from Laravel code. If it's just passing through from the database and almost no modification from the data, it'll be fast.

The data fetched by the users are not unique. Let's say you have a news site without user personalization. the news that the users fetched mostly will be the same. You cached the data from memory (Redis, which I recommend) or from the web server(Nginx, should be avoided), your Laravel program will run fast enough.

Querying directly from the database is faster than using Laravel ORM. you might consider it if needed, but I myself will always try to use ORM because it will help code to be more readable and secure.

Splitting database, web server, CDN, and cache server is obviously making it easier to monitor server usage.

Try to upgrade it to the latest version. I used to work with a company that using version 5, and it's not really good at performance.

opcode caching. cache the PHP file code. I myself never use this.

split app to backend and frontend. use state management for front end app to reduce requests data to the server.

Now let's answer your question

Are there any tools for checking performance? You can check Laravel debug bar, these tools provide for simple performance reports. I myself encourage you to make a test for each of the features you create. You can create a report from that unit test to find which feature taking time to finish.

Are lume faster than laravel? Yeah, Lumen is faster because they disabled some features from Laravel. But please be aware that Taylor seems gonna stop Lumen for development. You should consider this for the future.

If you're aware of performance, you might not choose Laravel for development.

Because there is a delay between each server while opening a connection. Whenever a user creating a request, they open a connection to the server. server open connections to the cache server, database server, SMTP server, or probably other 3rd parties as well. It's the real bottleneck that happened on Laravel. You can make keep-alive connections with the database and cache server to reduce connection delay, but you wouldn't find it in Laravel because it will dispose the connection whenever the request finish.

It's a typed language, mostly compiled language are faster

In the end, you might not be able to use Laravel with that server resources unless you're creating a really simple application.

Body:
I wanted to know that if 1000 users are concurrently using a website built with laravel 5 and also querying database regularly then how does laravel 5 perform ?
I know it would be slow but will it be highly slow that it would be unbearable ?
Note that i am also going to use ajax a lot.

And lets assume i am using digital ocean cloud service with following configurations

2GB memory
2 vCPU
40GB SSD

I don't expect completely real figures as it is impossible to do so but at least provide some details whether i should go with laravel with some considerable performance.

Please also provide some some tools through which i can check the speed of my laravel 5 application as well as how it will perform when there is actual load as well as other tools through which i can test speed and performance.

And it would be great if someone has real experience of using laravel especially Laravel 5.

And what about Lumen does that really make application faster than laravel and how much ?


问:
Iterate over two arrays simultaneously in List
How can I iterate two array in a list:

```<code>struct ContentView: View {
    let colors = ["red", "green", "blue"]
    let names = ["John", "Apple", "Seed"]

    var body: some View {
        VStack {
            List(colors, id: \.self) { color in
                Text(color)
            }
        }
    }
}
</code>```

For example I need to have:
Text("\(color) - \(animal)")

My code would be like this (I know it's wrong but that's the idea):

```<code>    List(colors, animals id: \.self) { color, animal in
        Text("\(color) - \(animal)")
    }
</code>```

答:
I think this is all a bit cumbersome and creating types that don't need to be. For this reason SwiftUI has the ForEach Statement. The code can also look like this:

import SwiftUI

struct ContentView: View {

```<code>let colors = ["red", "blue", "black", "purple", "green"]
let names = ["Paul", "Chris", "Rob", "Terry", "Andy"]

var body: some View {

    List {
        ForEach(0 ..< colors.count) {
            Text("Name \(self.names[$0]) has favorite color \(self.colors[$0]).")
        }
        .onDelete(perform: deleteRow)
    }
}
</code>```

}

The result then looks like this:

Of course, both arrays need to have the same number of elements.

Body:
How can I iterate two array in a list:

struct ContentView: View {
    let colors = ["red", "green", "blue"]
    let names = ["John", "Apple", "Seed"]

    var body: some View {
        VStack {
            List(colors, id: \.self) { color in
                Text(color)
            }
        }
    }
}

For example I need to have:
Text("\(color) - \(animal)")

My code would be like this (I know it's wrong but that's the idea):

    List(colors, animals id: \.self) { color, animal in
        Text("\(color) - \(animal)")
    }

Body:
I think this is all a bit cumbersome and creating types that don't need to be. For this reason SwiftUI has the ForEach Statement. The code can also look like this:

import SwiftUI

struct ContentView: View {

let colors = ["red", "blue", "black", "purple", "green"]
let names = ["Paul", "Chris", "Rob", "Terry", "Andy"]

var body: some View {

    List {
        ForEach(0 ..< colors.count) {
            Text("Name \(self.names[$0]) has favorite color \(self.colors[$0]).")
        }
        .onDelete(perform: deleteRow)
    }
}

}

The result then looks like this:

Of course, both arrays need to have the same number of elements.


问:
Check what Program creates a file
Is there any way to see what program creates or deletes a file in Python? I know that you can write a program that prints out when a File was created/deleted/modified using watchdog but I want to know what program creates/deletes/modifies this file. Is this possible in Python?</p>

答:
```<code>import os
os.remove(fiile)
</code>```

This is how you remove  a file. Hope it helps

Title: Check what Program creates a file

Body:
import os
os.remove(fiile)

This is how you remove  a file. Hope it helps


问:
How to play the next Song after first finished Discord Bot
I'm trying to create a Discord music Bot with discord.py, I'm new to Python.
I don't know how to let the Bot automatically play the next song. I tried many different things.
This is my current code for playing one song:

```<code>vc.play(discord.FFmpegPCMAudio(executable="C:/FFmpeg/bin/ffmpeg.exe", source=sound + ".mp3"))
await message.channel.send("Spiele nun " + str(sound) +"weiter")
</code>```

With the above code I didn't get a problem.

答:
You should use the after parameter of the FFmpegPCMAudio function. This parameter takes a callable as an argument and executes it when the current song is over.

First, you have to create a song queue variable :

song_queue = []
```
<ul>
<li>Then, you'll have to change your <code>play()</code> function :</li>
</ul>
```source = sound + '.mp3'
soung_queue.append(source)
if not vc.is_playing():
    vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
    await ctx.send("Now playing...")
else:
    await ctx.send('Song queued')
```
<ul>
<li>Finally, you'll have to create a <code>play_next()</code> function :</li>
</ul>
<pre class="lang-py prettyprint-override"><code>import asyncio

def play_next(ctx, source):
    if len(self.song_queue) >= 1:
        del self.song_queue[0]
        vc = get(self.bot.voice_clients, guild=ctx.guild)
        vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
        asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."), self.bot.loop)
</code>```

You can name the play_next() function whatever you want.

If you want your bot to disconnect because it's been too long since it was playing sound, change the play_next() function to :

import asyncio

def play_next(ctx, source):
    vc = get(self.bot.voice_clients, guild=ctx.guild)
    if len(self.song_queue) >= 1:
        del self.song_queue[0]
        vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
    else:
        asyncio.sleep(90) #wait 1 minute and 30 seconds
        if not vc.is_playing():
            asyncio.run_coroutine_threadsafe(vc.disconnect(ctx), self.bot.loop)
            asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."), self.bot.loop)

```

Body:
I'm trying to create a Discord music Bot with discord.py, I'm new to Python.
I don't know how to let the Bot automatically play the next song. I tried many different things.
This is my current code for playing one song:

vc.play(discord.FFmpegPCMAudio(executable="C:/FFmpeg/bin/ffmpeg.exe", source=sound + ".mp3"))
await message.channel.send("Spiele nun " + str(sound) +"weiter")

With the above code I didn't get a problem.

Body:
You should use the after parameter of the FFmpegPCMAudio function. This parameter takes a callable as an argument and executes it when the current song is over.

First, you have to create a song queue variable :

song_queue = []

Then, you'll have to change your play() function :

source = sound + '.mp3'
soung_queue.append(source)
if not vc.is_playing():
    vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
    await ctx.send("Now playing...")
else:
    await ctx.send('Song queued')

Finally, you'll have to create a play_next() function :

import asyncio

def play_next(ctx, source):
    if len(self.song_queue) >= 1:
        del self.song_queue[0]
        vc = get(self.bot.voice_clients, guild=ctx.guild)
        vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
        asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."), self.bot.loop)

You can name the play_next() function whatever you want.

If you want your bot to disconnect because it's been too long since it was playing sound, change the play_next() function to :

import asyncio

def play_next(ctx, source):
    vc = get(self.bot.voice_clients, guild=ctx.guild)
    if len(self.song_queue) >= 1:
        del self.song_queue[0]
        vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
    else:
        asyncio.sleep(90) #wait 1 minute and 30 seconds
        if not vc.is_playing():
            asyncio.run_coroutine_threadsafe(vc.disconnect(ctx), self.bot.loop)
            asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."), self.bot.loop)


问:
postgres doesn't work inside docker container
I've been developing a webpage with golang using Postgres. I could run the app without a docker container and I could connect to the database, no problem occurred. However, when I dockerized my app and run it, Postgres showed an error: dial tcp 127.0.0.1:5432: connect: connection refused.

Connecting to postgres:

```<code>db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable")
</code>```

I searched for the internet and found that inside the container localhost will direct to the container. I tried to connect specifying the IP of my server:

```<code>db, err := sql.Open("postgres", "host=XXX.XXX.XX.XXX port=5432 user=postgres password=postgres dbname=postgres sslmode=disable")
</code>```

it also showed the same error:  dial tcp XXX.XXX.XX.XXX:5432: connect: connection refused

when I run it without dockerizing it works fine.
 What to do?

Here is my dockerfile. I was just trying to upload the simplest app to the dedicated server. I logged in using ssh root@IP and installed go and postgres. I pulled my app to the server and then started it with just go build and ./app. Everything worked fine.  Now I wanna run it using the dockerfile below.

FROM golang:alpine
RUN mkdir /app
ADD . /app
WORKDIR /app
COPY go.mod .
RUN go mod download
COPY . .
RUN go build -o main .
CMD ["/app/main"]

答:
After thoroughly checking the comments by @colm.anseo, I figured out how to access the host machine in the docker container. I used the flag
--network="host" to run my docker container. So I used:
docker run -it --network="host" myapp to run the container. As I understood, this will
bind the IP of the docker container and host machine

you can read more about it in: From inside of a Docker container, how do I connect to the localhost of the machine?

Body:
I've been developing a webpage with golang using Postgres. I could run the app without a docker container and I could connect to the database, no problem occurred. However, when I dockerized my app and run it, Postgres showed an error: dial tcp 127.0.0.1:5432: connect: connection refused.

Connecting to postgres:

db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable")

I searched for the internet and found that inside the container localhost will direct to the container. I tried to connect specifying the IP of my server:

db, err := sql.Open("postgres", "host=XXX.XXX.XX.XXX port=5432 user=postgres password=postgres dbname=postgres sslmode=disable")

it also showed the same error:  dial tcp XXX.XXX.XX.XXX:5432: connect: connection refused

when I run it without dockerizing it works fine.
 What to do?

Here is my dockerfile. I was just trying to upload the simplest app to the dedicated server. I logged in using ssh root@IP and installed go and postgres. I pulled my app to the server and then started it with just go build and ./app. Everything worked fine.  Now I wanna run it using the dockerfile below.

FROM golang:alpine
RUN mkdir /app
ADD . /app
WORKDIR /app
COPY go.mod .
RUN go mod download
COPY . .
RUN go build -o main .
CMD ["/app/main"]


问:
Add Reference Library to an outside MS Access Database
I have a code that creates new MS Access Databases. I'd like to add reference libraries to these newly created MS Access Databases.
Here is the code that I wrote but is not working:

```<code>Sub makeDb(fl As String)
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")

'check if the file already exists

If fs.FileExists(fl) = False Then

    'create new ms access database

    Dim accessApp As Access.Application
    Set accessApp = New Access.Application
    accessApp.DBEngine.CreateDatabase fl, dbLangGeneral

    'loop through all references in current database and add them to the newly created dbs

    Dim cur_vbProj As VBIDE.VBProject: Set cur_vbProj = Application.VBE.VBProjects(1)
    Dim cur_vbRefs As VBIDE.References: Set cur_vbRefs = cur_vbProj.References
    Dim cur_vbRef As VBIDE.Reference

    For Each cur_vbRef In cur_vbRefs
        Dim cur_guid As String: cur_guid = cur_vbRef.Guid
        Dim cur_major As Long: cur_major = cur_vbRef.Major
        Dim cur_minor As Long: cur_minor = cur_vbRef.Minor

        'here is the code that doesn't work

        Dim vbProj As VBIDE.VBProject: Set vbProj = accessApp.Application.VBE.VBProjects(1)
        Dim vbRefs As VBIDE.References: Set vbRefs = vbProj.References
        vbRefs.AddFromGuid Guid:=cur_guid, Major:=cur_major, Minor:=cur_minor

    Next

    accessApp.Quit
    Set accessApp = Nothing

End If

End Sub
</code>```

The line Set vbProj = accessApp.Application.VBE.VBProjects(1) throws Run-Time error '9' Subscript out of range. How should I modify the code? Is it even possible to add references to an outside database?

答:
Following works for me:</p>

```<code>Sub makeDb(f1 As String)
Dim accApp As Access.Application
Dim cur_vbRefs As References
Dim cur_vbRef As Reference
If Dir(f1) = "" Then
    Access.DBEngine.CreateDatabase f1, dbLangGeneral
    Set accApp = New Access.Application
    accApp.OpenCurrentDatabase f1
    'loop through all references in current database and add them to the newly created dbs
    Set cur_vbRefs = Application.References
    For Each cur_vbRef In cur_vbRefs
        On Error Resume Next
        accApp.References.AddFromGuid cur_vbRef.Guid, cur_vbRef.Major, cur_vbRef.Minor
    Next
End If
End Sub
</code>```

Body:
I have a code that creates new MS Access Databases. I'd like to add reference libraries to these newly created MS Access Databases.
Here is the code that I wrote but is not working:

Sub makeDb(fl As String)
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")

'check if the file already exists

If fs.FileExists(fl) = False Then

    'create new ms access database

    Dim accessApp As Access.Application
    Set accessApp = New Access.Application
    accessApp.DBEngine.CreateDatabase fl, dbLangGeneral

    'loop through all references in current database and add them to the newly created dbs

    Dim cur_vbProj As VBIDE.VBProject: Set cur_vbProj = Application.VBE.VBProjects(1)
    Dim cur_vbRefs As VBIDE.References: Set cur_vbRefs = cur_vbProj.References
    Dim cur_vbRef As VBIDE.Reference

    For Each cur_vbRef In cur_vbRefs
        Dim cur_guid As String: cur_guid = cur_vbRef.Guid
        Dim cur_major As Long: cur_major = cur_vbRef.Major
        Dim cur_minor As Long: cur_minor = cur_vbRef.Minor

        'here is the code that doesn't work

        Dim vbProj As VBIDE.VBProject: Set vbProj = accessApp.Application.VBE.VBProjects(1)
        Dim vbRefs As VBIDE.References: Set vbRefs = vbProj.References
        vbRefs.AddFromGuid Guid:=cur_guid, Major:=cur_major, Minor:=cur_minor

    Next

    accessApp.Quit
    Set accessApp = Nothing

End If

End Sub

The line Set vbProj = accessApp.Application.VBE.VBProjects(1) throws Run-Time error '9' Subscript out of range. How should I modify the code? Is it even possible to add references to an outside database?

Body:
Following works for me:

Sub makeDb(f1 As String)
Dim accApp As Access.Application
Dim cur_vbRefs As References
Dim cur_vbRef As Reference
If Dir(f1) = "" Then
    Access.DBEngine.CreateDatabase f1, dbLangGeneral
    Set accApp = New Access.Application
    accApp.OpenCurrentDatabase f1
    'loop through all references in current database and add them to the newly created dbs
    Set cur_vbRefs = Application.References
    For Each cur_vbRef In cur_vbRefs
        On Error Resume Next
        accApp.References.AddFromGuid cur_vbRef.Guid, cur_vbRef.Major, cur_vbRef.Minor
    Next
End If
End Sub


问:
Get data from request npm
I'm building an app using express js and using request(v-2.88.2) to get data from an api

```<code>request(url, function(error, request, body) {
    var data = JSON.parse(body);
});
</code>```

I want to use var data in other functions.

Are there any ways to do this?

答:
If you want to use data in other functions just pass as arguments in that functions i.e.

```<code>request(url, function(error, request, body) {
    var data = JSON.parse(body);
    // call another function and pass as arguments
    antoherFunctions(data);

});

function anotherFunctions(data){
  // use data as per requirement
  request(data.url, function(error, request, body) {
    var anotherData = JSON.parse(body);
    console.log(anotherData)
  });
}
</code>```

Title: Get data from request npm

Body:
I'm building an app using express js and using request(v-2.88.2) to get data from an api

request(url, function(error, request, body) {
    var data = JSON.parse(body);
});

I want to use var data in other functions.

Are there any ways to do this?

Body:
If you want to use data in other functions just pass as arguments in that functions i.e.

request(url, function(error, request, body) {
    var data = JSON.parse(body);
    // call another function and pass as arguments
    antoherFunctions(data);

});

function anotherFunctions(data){
  // use data as per requirement
  request(data.url, function(error, request, body) {
    var anotherData = JSON.parse(body);
    console.log(anotherData)
  });
}


答:
Sure, it would be hard to do much if you couldn't.</p>

```<code>function doStuffWithData(theData) {
  // This is your other function

  // E.g. make another dependent request
  const secondRequestUrl = theData.url;
  request(secondRequestUrl, function(error, request, body) {
    var evenMoreData = JSON.parse(body);
    // Do even more stuff with your second request's results
  });
}

request(url, function(error, request, body) {
  var data = JSON.parse(body);

  // Use data in another function:
  doStuffWithData(data);
});
</code>```

Title: Get data from request npm

Body:
Sure, it would be hard to do much if you couldn't.

function doStuffWithData(theData) {
  // This is your other function

  // E.g. make another dependent request
  const secondRequestUrl = theData.url;
  request(secondRequestUrl, function(error, request, body) {
    var evenMoreData = JSON.parse(body);
    // Do even more stuff with your second request's results
  });
}

request(url, function(error, request, body) {
  var data = JSON.parse(body);

  // Use data in another function:
  doStuffWithData(data);
});


问:
Why do I get "Invalid read of size 8"? (Valgrind)
I already read similar posts on Stackoverflow but they do not solve my problem.

My problem

I get the following error message from Valgrind when I run the debug version of the executable with Valgrind.

```<code>==16631== Invalid read of size 8
==16631==    at 0x217890: std::__detail::__variant::_Uninitialized<long long, true>::_Uninitialized<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:222)
==16631==    by 0x2178C9: std::__detail::__variant::_Variadic_union<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variadic_union<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:342)
==16631==    by 0x2178FD: std::__detail::__variant::_Variant_storage<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:399)
==16631==    by 0x2156F0: std::__detail::__variant::_Copy_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:504)
==16631==    by 0x215716: std::__detail::__variant::_Move_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:532)
==16631==    by 0x21573C: std::__detail::__variant::_Copy_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:592)
==16631==    by 0x215762: std::__detail::__variant::_Move_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:649)
==16631==    by 0x215791: std::__detail::__variant::_Variant_base<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_base<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:701)
==16631==    by 0x213F29: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<0ul, long long const&, long long, void>(std::in_place_index_t<0ul>, long long const&) (variant:1398)
==16631==    by 0x213F6B: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<long long const&, void, void, long long, void>(long long const&) (variant:1369)
==16631==    by 0x20B8ED: tgbot::Endpoints::deleteMessage(long long const&, int const&) const (Endpoints.cpp:1957)
==16631==    by 0x2B17F6: ChatCleaner::run(std::shared_ptr<tgbot::Bot> const&) (ChatCleaner.cpp:40)
==16631==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==16631==
==16631==
==16631== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==16631==  Access not within mapped region at address 0x0
==16631==    at 0x217890: std::__detail::__variant::_Uninitialized<long long, true>::_Uninitialized<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:222)
==16631==    by 0x2178C9: std::__detail::__variant::_Variadic_union<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variadic_union<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:342)
==16631==    by 0x2178FD: std::__detail::__variant::_Variant_storage<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:399)
==16631==    by 0x2156F0: std::__detail::__variant::_Copy_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:504)
==16631==    by 0x215716: std::__detail::__variant::_Move_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:532)
==16631==    by 0x21573C: std::__detail::__variant::_Copy_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:592)
==16631==    by 0x215762: std::__detail::__variant::_Move_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:649)
==16631==    by 0x215791: std::__detail::__variant::_Variant_base<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_base<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:701)
==16631==    by 0x213F29: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<0ul, long long const&, long long, void>(std::in_place_index_t<0ul>, long long const&) (variant:1398)
==16631==    by 0x213F6B: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<long long const&, void, void, long long, void>(long long const&) (variant:1369)
==16631==    by 0x20B8ED: tgbot::Endpoints::deleteMessage(long long const&, int const&) const (Endpoints.cpp:1957)
==16631==    by 0x2B17F6: ChatCleaner::run(std::shared_ptr<tgbot::Bot> const&) (ChatCleaner.cpp:40)
==16631==  If you believe this happened as a result of a stack
==16631==  overflow in your program's main thread (unlikely but
==16631==  possible), you can try to increase the size of the
==16631==  main thread stack using the --main-stacksize= flag.
==16631==  The main thread stack size used in this run was 8388608.
==16631==
==16631== HEAP SUMMARY:
==16631==     in use at exit: 317,149 bytes in 4,488 blocks
==16631==   total heap usage: 1,171,900 allocs, 1,167,412 frees, 359,098,054 bytes allocated
==16631==
==16631== LEAK SUMMARY:
==16631==    definitely lost: 0 bytes in 0 blocks
==16631==    indirectly lost: 0 bytes in 0 blocks
==16631==      possibly lost: 0 bytes in 0 blocks
==16631==    still reachable: 317,045 bytes in 4,487 blocks
==16631==         suppressed: 104 bytes in 1 blocks
==16631== Reachable blocks (those to which a pointer was found) are not shown.
==16631== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==16631==
==16631== For lists of detected and suppressed errors, rerun with: -s
==16631== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Speicherzugriffsfehler (Speicherabzug geschrieben)
</code>```

The suitable source code

"m_msgs_to_delete" is a static vector in the class ChatCleaner.

```<code>32void ChatCleaner::run(const tgbot::Bot::ptr &bot) noexcept
33{
34  if(!m_msgs_to_delete.empty())
35  {
36      //Reverse to have the oldest message at the end.
37      std::reverse(m_msgs_to_delete.begin(), m_msgs_to_delete.end());
38
39      //Delete the message.
40      bot->get_endpnts()->deleteMessage(m_msgs_to_delete.at(m_msgs_to_delete.size() - 1)->chat->id, m_msgs_to_delete.at(m_msgs_to_delete.size() - 1)->message_id);
41      m_msgs_to_delete.pop_back();
42
43      //Reverse again.
44      std::reverse(m_msgs_to_delete.begin(), m_msgs_to_delete.end());
45
46      m_last_time = tools::Tools::get_time();
47      m_msgs_to_delete.shrink_to_fit();
48  }
49}
</code>```

```<code>1953    bool Endpoints::deleteMessage(const long long &chat_id, const int &message_id) const noexcept
    {
        //HTTP arguments
        std::vector<tools::HttpArg> http_args;
1957        http_args.push_back(tools::HttpArg("chat_id", chat_id));
        http_args.push_back(tools::HttpArg("message_id", message_id));

        tools::HttpClient http_client("https://api.telegram.org/bot" + m_token + "/deleteMessage", http_args);
        std::string json = http_client.send_post_req_multipart().m_body;

1963        rapidjson::Document doc;
        doc.Parse(json.c_str());

        if(doc.IsObject())
            if(doc.HasMember("result"))
                if(doc["result"].IsBool())
1969                    return doc["result"].GetBool();
                else
                    tools::Tools::write_err_log(Messages::field_does_not_contain_bool("result"));
            else
                tools::Tools::write_err_log_tmp(Messages::field_non_existent("result"));
        else
            tools::Tools::write_err_log(Messages::server_resp_not_json_object);
1976
1977        return false;
1978    }
</code>```

From what I see the error occurs in line 40 of the snippet above as that is an excerpt from the file ChatCleaner.cpp. This line accesses a vector which can totally be the error as users with similar problems on Stackoverflow also had problems with vector or array accessing. Unfortunately, I cannot see what I did wrong. This error error happens absolutely arbitrarily and I cannot reproduce it.

Additional notes that might help

The code is from a my chat bot for Telegram which runs 24/7.

The error can happen a few minutes after starting the software or after days or weeks.

The vector contains std::shared_ptr<> of sent messages which shall be deleted after a while.

I already checked whether the vector content may be broken which was not the case when the error occurred. The chat and message ID were totally fine. I highly assume that is just a memory accessing problem but I cannot figure out the soure of the problem.

Question

What is the cause of the problem?

答:
I finally found the source of the problem with the help of the hints @cdhowie gave. The member variable "chat" of the Message object caused the problem since as you can see here

```<code>if(doc.HasMember("chat"))
{
    if(doc["chat"].IsObject())
        chat = std::make_shared<Chat>(tools::Tools::get_json_as_string(doc["chat"]));
    else
        tools::Tools::write_err_log(Messages::field_does_not_contain_json_obj("chat"));
}
</code>```

this part of the Message constructor only creates a chat instance if the passed HTTP response body contains the proper field. Therefore, this member access m_msgs_to_delete.at(m_msgs_to_delete.size() - 1)->chat->id in line 40 of ChatCleaner.cpp called a null pointer as "chat" does not exist on the heap in this case.

PS: The object doc above comes from the library rapidjson. The definition is rapidjson::Document doc;. Its purpose is parsing JSON objects and making data accessible. The whole source code is from my Telegram chat bot.

Body:
I already read similar posts on Stackoverflow but they do not solve my problem.

My problem

I get the following error message from Valgrind when I run the debug version of the executable with Valgrind.

==16631== Invalid read of size 8
==16631==    at 0x217890: std::__detail::__variant::_Uninitialized<long long, true>::_Uninitialized<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:222)
==16631==    by 0x2178C9: std::__detail::__variant::_Variadic_union<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variadic_union<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:342)
==16631==    by 0x2178FD: std::__detail::__variant::_Variant_storage<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:399)
==16631==    by 0x2156F0: std::__detail::__variant::_Copy_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:504)
==16631==    by 0x215716: std::__detail::__variant::_Move_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:532)
==16631==    by 0x21573C: std::__detail::__variant::_Copy_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:592)
==16631==    by 0x215762: std::__detail::__variant::_Move_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:649)
==16631==    by 0x215791: std::__detail::__variant::_Variant_base<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_base<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:701)
==16631==    by 0x213F29: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<0ul, long long const&, long long, void>(std::in_place_index_t<0ul>, long long const&) (variant:1398)
==16631==    by 0x213F6B: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<long long const&, void, void, long long, void>(long long const&) (variant:1369)
==16631==    by 0x20B8ED: tgbot::Endpoints::deleteMessage(long long const&, int const&) const (Endpoints.cpp:1957)
==16631==    by 0x2B17F6: ChatCleaner::run(std::shared_ptr<tgbot::Bot> const&) (ChatCleaner.cpp:40)
==16631==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==16631==
==16631==
==16631== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==16631==  Access not within mapped region at address 0x0
==16631==    at 0x217890: std::__detail::__variant::_Uninitialized<long long, true>::_Uninitialized<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:222)
==16631==    by 0x2178C9: std::__detail::__variant::_Variadic_union<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variadic_union<long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:342)
==16631==    by 0x2178FD: std::__detail::__variant::_Variant_storage<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:399)
==16631==    by 0x2156F0: std::__detail::__variant::_Copy_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:504)
==16631==    by 0x215716: std::__detail::__variant::_Move_ctor_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:532)
==16631==    by 0x21573C: std::__detail::__variant::_Copy_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:592)
==16631==    by 0x215762: std::__detail::__variant::_Move_assign_base<false, long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_storage<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:649)
==16631==    by 0x215791: std::__detail::__variant::_Variant_base<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::_Variant_base<0ul, long long const&>(std::in_place_index_t<0ul>, long long const&) (variant:701)
==16631==    by 0x213F29: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<0ul, long long const&, long long, void>(std::in_place_index_t<0ul>, long long const&) (variant:1398)
==16631==    by 0x213F6B: std::variant<long long, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::shared_ptr<tools::InputFile> >::variant<long long const&, void, void, long long, void>(long long const&) (variant:1369)
==16631==    by 0x20B8ED: tgbot::Endpoints::deleteMessage(long long const&, int const&) const (Endpoints.cpp:1957)
==16631==    by 0x2B17F6: ChatCleaner::run(std::shared_ptr<tgbot::Bot> const&) (ChatCleaner.cpp:40)
==16631==  If you believe this happened as a result of a stack
==16631==  overflow in your program's main thread (unlikely but
==16631==  possible), you can try to increase the size of the
==16631==  main thread stack using the --main-stacksize= flag.
==16631==  The main thread stack size used in this run was 8388608.
==16631==
==16631== HEAP SUMMARY:
==16631==     in use at exit: 317,149 bytes in 4,488 blocks
==16631==   total heap usage: 1,171,900 allocs, 1,167,412 frees, 359,098,054 bytes allocated
==16631==
==16631== LEAK SUMMARY:
==16631==    definitely lost: 0 bytes in 0 blocks
==16631==    indirectly lost: 0 bytes in 0 blocks
==16631==      possibly lost: 0 bytes in 0 blocks
==16631==    still reachable: 317,045 bytes in 4,487 blocks
==16631==         suppressed: 104 bytes in 1 blocks
==16631== Reachable blocks (those to which a pointer was found) are not shown.
==16631== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==16631==
==16631== For lists of detected and suppressed errors, rerun with: -s
==16631== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Speicherzugriffsfehler (Speicherabzug geschrieben)

The suitable source code

"m_msgs_to_delete" is a static vector in the class ChatCleaner.

32void ChatCleaner::run(const tgbot::Bot::ptr &bot) noexcept
33{
34  if(!m_msgs_to_delete.empty())
35  {
36      //Reverse to have the oldest message at the end.
37      std::reverse(m_msgs_to_delete.begin(), m_msgs_to_delete.end());
38
39      //Delete the message.
40      bot->get_endpnts()->deleteMessage(m_msgs_to_delete.at(m_msgs_to_delete.size() - 1)->chat->id, m_msgs_to_delete.at(m_msgs_to_delete.size() - 1)->message_id);
41      m_msgs_to_delete.pop_back();
42
43      //Reverse again.
44      std::reverse(m_msgs_to_delete.begin(), m_msgs_to_delete.end());
45
46      m_last_time = tools::Tools::get_time();
47      m_msgs_to_delete.shrink_to_fit();
48  }
49}

1953    bool Endpoints::deleteMessage(const long long &chat_id, const int &message_id) const noexcept
    {
        //HTTP arguments
        std::vector<tools::HttpArg> http_args;
1957        http_args.push_back(tools::HttpArg("chat_id", chat_id));
        http_args.push_back(tools::HttpArg("message_id", message_id));

        tools::HttpClient http_client("https://api.telegram.org/bot" + m_token + "/deleteMessage", http_args);
        std::string json = http_client.send_post_req_multipart().m_body;

1963        rapidjson::Document doc;
        doc.Parse(json.c_str());

        if(doc.IsObject())
            if(doc.HasMember("result"))
                if(doc["result"].IsBool())
1969                    return doc["result"].GetBool();
                else
                    tools::Tools::write_err_log(Messages::field_does_not_contain_bool("result"));
            else
                tools::Tools::write_err_log_tmp(Messages::field_non_existent("result"));
        else
            tools::Tools::write_err_log(Messages::server_resp_not_json_object);
1976
1977        return false;
1978    }

From what I see the error occurs in line 40 of the snippet above as that is an excerpt from the file ChatCleaner.cpp. This line accesses a vector which can totally be the error as users with similar problems on Stackoverflow also had problems with vector or array accessing. Unfortunately, I cannot see what I did wrong. This error error happens absolutely arbitrarily and I cannot reproduce it.

Additional notes that might help

The code is from a my chat bot for Telegram which runs 24/7.

The error can happen a few minutes after starting the software or after days or weeks.

The vector contains std::shared_ptr<> of sent messages which shall be deleted after a while.

I already checked whether the vector content may be broken which was not the case when the error occurred. The chat and message ID were totally fine. I highly assume that is just a memory accessing problem but I cannot figure out the soure of the problem.

Question

What is the cause of the problem?

Body:
I finally found the source of the problem with the help of the hints @cdhowie gave. The member variable "chat" of the Message object caused the problem since as you can see here

if(doc.HasMember("chat"))
{
    if(doc["chat"].IsObject())
        chat = std::make_shared<Chat>(tools::Tools::get_json_as_string(doc["chat"]));
    else
        tools::Tools::write_err_log(Messages::field_does_not_contain_json_obj("chat"));
}

this part of the Message constructor only creates a chat instance if the passed HTTP response body contains the proper field. Therefore, this member access m_msgs_to_delete.at(m_msgs_to_delete.size() - 1)->chat->id in line 40 of ChatCleaner.cpp called a null pointer as "chat" does not exist on the heap in this case.

PS: The object doc above comes from the library rapidjson. The definition is rapidjson::Document doc;. Its purpose is parsing JSON objects and making data accessible. The whole source code is from my Telegram chat bot.


问:
Is it possible to keep appsettings.json editable post-deployment when using the "Produce single file" publish option for VS2019 / .Net Core 3.1?
I have a simple console app which needs to load its configuration from appsettings.json. I'm publishing from VS2019 using the "Produce single file" option.

The default behaviour is for publish to place appsettings.json inside the single file. That's no good to me because I want to be able to edit the configuration file in-place on the Linux server where it will be deployed.

It's possible to exclude appsettings.json from the bundled file by adding an option to its entry in the project file - <ExcludeFromSingleFile>true</ExcludeFromSingleFile> works great and causes VS2019 to publish the appsettings.json file alongside the binary.

However...

When I run the binary (from /opt/MyApp/MyApp), and log the location from which it's trying to load appsettings.json, I see:

```<code>Loading settings from /var/tmp/.net/MyApp/jq1u11uk.4ap/appsettings.json
</code>```

So my edited /opt/MyApp/appsettings.json is being ignored.

Is there some intended way to keep appsettings.json editable when using this publish option?

(This question was also asked at How to handle Appsettings for .net core 3.1 self contained single file publish, but was never answered in a way that solves being able to edit the file in-place.)

答: Turns out that this has been solved elsewhere - now working well after following this answer: https://stackoverflow.com/a/58307732/2847257</p>

Body:
I have a simple console app which needs to load its configuration from appsettings.json. I'm publishing from VS2019 using the "Produce single file" option.

The default behaviour is for publish to place appsettings.json inside the single file. That's no good to me because I want to be able to edit the configuration file in-place on the Linux server where it will be deployed.

It's possible to exclude appsettings.json from the bundled file by adding an option to its entry in the project file - <ExcludeFromSingleFile>true</ExcludeFromSingleFile> works great and causes VS2019 to publish the appsettings.json file alongside the binary.

However...

When I run the binary (from /opt/MyApp/MyApp), and log the location from which it's trying to load appsettings.json, I see:

Loading settings from /var/tmp/.net/MyApp/jq1u11uk.4ap/appsettings.json

So my edited /opt/MyApp/appsettings.json is being ignored.

Is there some intended way to keep appsettings.json editable when using this publish option?

(This question was also asked at How to handle Appsettings for .net core 3.1 self contained single file publish, but was never answered in a way that solves being able to edit the file in-place.)


问:
Python - Kivy - Python has stopped working during installation of kivy
I was trying to install kivy to try out the GUI application using python, however after installing Visual Studio C++ 141 build and trying to install kivy using python -m pip install kivy I get the python has stopped working pop-up.
Anyone knows what might be a problem?
Thanks in advance.

答:
Quick solution will be using kivy master branch directly rather than waiting for the wheel update.

Run the below command:

```<code>pip install kivy[base] kivy_examples --pre --extra-index-url https://kivy.org/downloads/simple/
</code>```

Body:
Quick solution will be using kivy master branch directly rather than waiting for the wheel update.

Run the below command:

pip install kivy[base] kivy_examples --pre --extra-index-url https://kivy.org/downloads/simple/


问:
File Picker for Android
Is there any picker available to pick file from the SDCard or Device memory,like FilePicker available in Blackberry?
If not ,then any alternative for doing this?

Please help me.
Thanks in advance.

答:
Although there are several out there on web, but the one that I personally use is IO file manager its easy to use and integrate

Update: Link to latest repo

Title: File Picker for Android


问:
Swift - How do I count the occurrences of a specific character in a String?
Let's say that I have a specific String like follows:

```<code>var myName = "Jane Doe"
</code>```

I want to count the number of times that a specific character shows up in the String, such as the amount of times that the letter "e" shows up. How can I do this?

答:
To count the occurrences of a specific character all you have to do is use the filter() method like so:

```<code>var myName = "Jane Doe"
let numOccurrences = myName.filter{ $0 == "e" }.count
print(numOccurrences) // prints out 2
</code>```

.filter will iterate over every character in the string, denoted by $0, and then return a list of all characters that are equal to the character "e". All you have to do after that is use .count to get the number of total occurrences.

Body:
Let's say that I have a specific String like follows:

var myName = "Jane Doe"

I want to count the number of times that a specific character shows up in the String, such as the amount of times that the letter "e" shows up. How can I do this?

Body:
To count the occurrences of a specific character all you have to do is use the filter() method like so:

var myName = "Jane Doe"
let numOccurrences = myName.filter{ $0 == "e" }.count
print(numOccurrences) // prints out 2

.filter will iterate over every character in the string, denoted by $0, and then return a list of all characters that are equal to the character "e". All you have to do after that is use .count to get the number of total occurrences.


问:
Required attribute and type email dows not work. ReactJS and Materia UI
I'm new in ReactJS and Material-UI and I'm trying to build a normal form just for fun, but some attributes does not work and I really can't understand why

Here's the code:

```<code>import React, { Component } from 'react';import { makeStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import AccountCircle from '@material-ui/icons/AccountCircle';
import LockIcon from '@material-ui/icons/Lock';
import EmailIcon from '@material-ui/icons/Email';
import PaymentIcon from '@material-ui/icons/Payment';
import TodayIcon from '@material-ui/icons/Today';
import moduleName from '@material-ui/core/';

export class FormOpzioniPagamento extends Component {

    continue = e =>{
        e.preventDefault();
        this.props.nextStep();
    };
    render() {
        const {values,handleChange}=this.props;
        return (
            <div align="center">
            <Avatar alt="Remy Sharp" src="https://i1.rgstatic.net/ii/profile.image/363082749628419-1463577081575_Q512/Rosario_Sorbello2.jpg" align="center"/>
            <FormControl>
            <FormControl required>
                <InputLabel htmlFor="input-with-icon-adornment" color="secondary">Nome</InputLabel>
                <Input
                required
                id="input-with-icon-adornment"
                color="secondary"
                startAdornment={
                    <InputAdornment position="start">
                    <AccountCircle />
                    </InputAdornment>
                }
                onChange={handleChange('nome')}
                /></FormControl>
               </div>
export default FormOpzioniPagamento

</code>```

It just allows me to continue without any problem

答:
the code you have provide that is buggy code. Please try this example:

```<code>import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import AccountCircle from '@material-ui/icons/AccountCircle';
import LockIcon from '@material-ui/icons/Lock';
import EmailIcon from '@material-ui/icons/Email';
import PaymentIcon from '@material-ui/icons/Payment';
import TodayIcon from '@material-ui/icons/Today';
import Avatar from "@material-ui/core/Avatar";
import InputLabel from "@material-ui/core/InputLabel";
import Input from "@material-ui/core/Input";
import React from "react";
import Button from "@material-ui/core/Button";

export default class FormExample extends React.Component {

    nextStep = () => {
        alert('nextStep is called');
    };
    handleChange = (message) => {
        alert('handleChange is called. The parameter is: ' + message);
    };

    render() {
        return (
            <div>
                <FormOpzioniPagamento nextStep={this.nextStep} handleChange={this.handleChange}/>
            </div>
        );
    }
}

class FormOpzioniPagamento extends React.Component {

    continue = e => {
        e.preventDefault();
        this.props.nextStep();
    };

    render() {
        const {values, handleChange} = this.props;
        return (
            <div align="center">
                <Avatar alt="Remy Sharp"
                        src="https://i1.rgstatic.net/ii/profile.image/363082749628419-1463577081575_Q512/Rosario_Sorbello2.jpg"
                        align="center"/>
                <FormControl required>
                    <InputLabel htmlFor="input-with-icon-adornment" color="secondary">Nome</InputLabel>
                    <Input
                        required
                        id="input-with-icon-adornment"
                        color="secondary"
                        startAdornment={
                            <InputAdornment position="start">
                                <AccountCircle/>
                            </InputAdornment>
                        }
                        onChange={handleChange('nome')}
                    />
                    <Button color={"primary"} onClick={()=>{handleChange('submit') }}>Submit</Button>
                </FormControl>
            </div>
        );
    }
}
</code>```

Here is the Code Sandbox

Body:
I'm new in ReactJS and Material-UI and I'm trying to build a normal form just for fun, but some attributes does not work and I really can't understand why

Here's the code:

import React, { Component } from 'react';import { makeStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import AccountCircle from '@material-ui/icons/AccountCircle';
import LockIcon from '@material-ui/icons/Lock';
import EmailIcon from '@material-ui/icons/Email';
import PaymentIcon from '@material-ui/icons/Payment';
import TodayIcon from '@material-ui/icons/Today';
import moduleName from '@material-ui/core/';

export class FormOpzioniPagamento extends Component {

    continue = e =>{
        e.preventDefault();
        this.props.nextStep();
    };
    render() {
        const {values,handleChange}=this.props;
        return (

            <Avatar alt="Remy Sharp" src="https://i1.rgstatic.net/ii/profile.image/363082749628419-1463577081575_Q512/Rosario_Sorbello2.jpg" align="center"/>
            <FormControl>
            <FormControl required>
                <InputLabel htmlFor="input-with-icon-adornment" color="secondary">Nome</InputLabel>
                <Input
                required
                id="input-with-icon-adornment"
                color="secondary"
                startAdornment={
                    <InputAdornment position="start">
                    <AccountCircle />
                    </InputAdornment>
                }
                onChange={handleChange('nome')}
                /></FormControl>

export default FormOpzioniPagamento

It just allows me to continue without any problem

Body:
the code you have provide that is buggy code. Please try this example:

import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import AccountCircle from '@material-ui/icons/AccountCircle';
import LockIcon from '@material-ui/icons/Lock';
import EmailIcon from '@material-ui/icons/Email';
import PaymentIcon from '@material-ui/icons/Payment';
import TodayIcon from '@material-ui/icons/Today';
import Avatar from "@material-ui/core/Avatar";
import InputLabel from "@material-ui/core/InputLabel";
import Input from "@material-ui/core/Input";
import React from "react";
import Button from "@material-ui/core/Button";

export default class FormExample extends React.Component {

    nextStep = () => {
        alert('nextStep is called');
    };
    handleChange = (message) => {
        alert('handleChange is called. The parameter is: ' + message);
    };

    render() {
        return (
            <div>
                <FormOpzioniPagamento nextStep={this.nextStep} handleChange={this.handleChange}/>
            </div>
        );
    }
}

class FormOpzioniPagamento extends React.Component {

    continue = e => {
        e.preventDefault();
        this.props.nextStep();
    };

    render() {
        const {values, handleChange} = this.props;
        return (
            <div align="center">
                <Avatar alt="Remy Sharp"
                        src="https://i1.rgstatic.net/ii/profile.image/363082749628419-1463577081575_Q512/Rosario_Sorbello2.jpg"
                        align="center"/>
                <FormControl required>
                    <InputLabel htmlFor="input-with-icon-adornment" color="secondary">Nome</InputLabel>
                    <Input
                        required
                        id="input-with-icon-adornment"
                        color="secondary"
                        startAdornment={
                            <InputAdornment position="start">
                                <AccountCircle/>
                            </InputAdornment>
                        }
                        onChange={handleChange('nome')}
                    />
                    <Button color={"primary"} onClick={()=>{handleChange('submit') }}>Submit</Button>
                </FormControl>
            </div>
        );
    }
}

Here is the Code Sandbox


问:
How to get last index in a map with some null items
I got a Map(int,List<String>) and some of the lists inside are null for example:

{1 = [example1, 2000, May 22, 2020] , 2 = [example2, 120, May 30, 2020] ,  4 = [example3, 120, May 30, 2020]}

so in my example the list in index 3 is null.

so I want do get the highest index in the map in my example it'll be 4.

答:
Using Java 8 stream.

You can stream over the keyset of the map and call the max operation on that stream. Check the snippet below:

```<code>import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HighestValueInMap {
    public static void main(String[] args) {
        Map<Integer, List<String>> exampleMap = new HashMap<>();
        exampleMap.put(1, Arrays.asList("example1", "2000", "May 22", "2020"));
        exampleMap.put(2, Arrays.asList("example2", "120", "May 30", "2020"));
        exampleMap.put(4, Arrays.asList("example3", "120", "May 30", "2020"));
        System.out.println("exampleMap is = " + exampleMap);
        Integer max = exampleMap.keySet().stream().mapToInt(v -> v).max().getAsInt();
        System.out.println("The max value present in the map is = " + max);
    }
}
</code>```

Body:
Using Java 8 stream.

You can stream over the keyset of the map and call the max operation on that stream. Check the snippet below:

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HighestValueInMap {
    public static void main(String[] args) {
        Map<Integer, List<String>> exampleMap = new HashMap<>();
        exampleMap.put(1, Arrays.asList("example1", "2000", "May 22", "2020"));
        exampleMap.put(2, Arrays.asList("example2", "120", "May 30", "2020"));
        exampleMap.put(4, Arrays.asList("example3", "120", "May 30", "2020"));
        System.out.println("exampleMap is = " + exampleMap);
        Integer max = exampleMap.keySet().stream().mapToInt(v -> v).max().getAsInt();
        System.out.println("The max value present in the map is = " + max);
    }
}


问:
How to know which WMS URL to use in Tableau
I'm trying to layer WMS from NOAA in Tableau. How do I know which URL to use from the provided file?

Provided File

Background Info

答:
Your first URL, the one with the WMS request to GetCapabilities has the right form (although you can usually optionally cutoff the URL right before the ? character) Tableau will add the GetCapabilities part of the request when needed if you don’t.

The problem is that it looks like NOAA’s server is not responding properly to that WMS request. You should see a response in XML format describing the server’s capabilities, layers etc

So I’d ask the people that own the server what is going on.


问:
check a int/string contains specific digits in it using regex
I have a string/integer X: 912035374356789

i want to check if X contains : 1, 2, 3, 4, 5, 6, 7, 8, 9, 0

occurrence order is not matter

How do check it using regular expression.
if there is any algorithm please mention, because i want to do it in minimum time complexity

```<code>Example
ex1: 61243456092 //false 7 & 8 not present
ex2: 864123456789 //false 0 is not present
ex3: 987601234567 //true all present
</code>```

答:
I would just use string.contains like this:

```<code>public static boolean checkString(String str) {
    for (int i = 0; i < 10; i++) {
        if (!str.contains(Integer.toString(i))) {
            return false;
        }
    }

    return true;
}
</code>```

I realize it's not a regular expression like you wanted, but I think it's the simplest answer.

Body:
I have a string/integer X: 912035374356789

i want to check if X contains : 1, 2, 3, 4, 5, 6, 7, 8, 9, 0

occurrence order is not matter

How do check it using regular expression.
if there is any algorithm please mention, because i want to do it in minimum time complexity

Example
ex1: 61243456092 //false 7 & 8 not present
ex2: 864123456789 //false 0 is not present
ex3: 987601234567 //true all present

Body:
I would just use string.contains like this:

public static boolean checkString(String str) {
    for (int i = 0; i < 10; i++) {
        if (!str.contains(Integer.toString(i))) {
            return false;
        }
    }

    return true;
}

I realize it's not a regular expression like you wanted, but I think it's the simplest answer.


问:
Adding column conditioning on the other columns
I want to create a new column z based on the values of x and y.  If x>y, z=y otherwise z=x.

```<code>x  y
3  4
5  2
6  6
1  7
9  4
</code>```

Output required:

```<code>x  y  z
3  4  3
5  2  2
6  6  6
1  7  1
9  4  4
</code>```

答:
Another option with fifelse in data.table

```<code>library(data.table)
setDT(dt)[, z := fifelse(x > y, y, x)]
</code>```

Body:
I want to create a new column z based on the values of x and y.  If x>y, z=y otherwise z=x.

x  y
3  4
5  2
6  6
1  7
9  4

Output required:

x  y  z
3  4  3
5  2  2
6  6  6
1  7  1
9  4  4

Body:
Another option with fifelse in data.table

library(data.table)
setDT(dt)[, z := fifelse(x > y, y, x)]


问:
Discord.js serverinfo offline online dnd error

const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['si']
        });
    }

    async run(message) {
            let sicon = message.guild.iconURL;
            const embed = new Discord.MessageEmbed()
            .setTitle(`Name Of Server:  ${message.guild}`)
            .setColor(0xFF0000)
            .addField('Name', message.guild.name, true)
            .addField('ID', message.guild.id, true)
            .addField('Owner', message.guild.owner, true)
            .addField('Owner ID', message.guild.owner.id, true)
            .addField('Region', message.guild.region, true)
            .addField('Members', message.guild.memberCount, true)
            .addField("Users Online:", `${guild.members.filter(m => m.user.presence.status === "online").size}`)
            .addField("Users DND:", `${guild.members.filter(m => m.user.presence.status === "dnd").size}`)
            .addField("Users Offline:", `${guild.members.filter(m => m.user.presence.status === "offline").size}`)
            .addField('You Joined', message.member.joinedAt, true)
            .addField('Created At', message.guild.createdAt, true)
            .setThumbnail(sicon);
            message.channel.send(embed);
    }

};
```

<p>// hey I need help with this could someone tell me what's wrong here is error message =></p>

<p>// Logged in as Zorek!</p>

<pre class="lang-js prettyprint-override"><code>(node:29228) UnhandledPromiseRejectionWarning: ReferenceError: guild is not defined
    at module.exports.run (C:\Users\xdswe\Desktop\Zero\src\commands\Utilities\Serverinfo.js:23:43)
    at MenuDocsClient.<anonymous> (C:\Users\xdswe\Desktop\Zero\src\Structures\MenuDocsClient.js:38:13)
    at MenuDocsClient.emit (events.js:311:20)
    at MessageCreateAction.handle (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:311:20)
</code>```

答:
guild is in fact not defined, you need to specify which guild you're trying to get the members collection from

.addField("Users Online:", `${message.guild.members.filter(m => m.user.presence.status === "online").size}`)
.addField("Users DND:", `${message.guild.members.filter(m => m.user.presence.status === "dnd").size}`)
.addField("Users Offline:", `${message.guild.members.filter(m => m.user.presence.status === "offline").size}`)
```

Body:
const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['si']
        });
    }

    async run(message) {
            let sicon = message.guild.iconURL;
            const embed = new Discord.MessageEmbed()
            .setTitle(`Name Of Server:  ${message.guild}`)
            .setColor(0xFF0000)
            .addField('Name', message.guild.name, true)
            .addField('ID', message.guild.id, true)
            .addField('Owner', message.guild.owner, true)
            .addField('Owner ID', message.guild.owner.id, true)
            .addField('Region', message.guild.region, true)
            .addField('Members', message.guild.memberCount, true)
            .addField("Users Online:", `${guild.members.filter(m => m.user.presence.status === "online").size}`)
            .addField("Users DND:", `${guild.members.filter(m => m.user.presence.status === "dnd").size}`)
            .addField("Users Offline:", `${guild.members.filter(m => m.user.presence.status === "offline").size}`)
            .addField('You Joined', message.member.joinedAt, true)
            .addField('Created At', message.guild.createdAt, true)
            .setThumbnail(sicon);
            message.channel.send(embed);
    }

};

// hey I need help with this could someone tell me what's wrong here is error message =>

// Logged in as Zorek!

(node:29228) UnhandledPromiseRejectionWarning: ReferenceError: guild is not defined
    at module.exports.run (C:\Users\xdswe\Desktop\Zero\src\commands\Utilities\Serverinfo.js:23:43)
    at MenuDocsClient.<anonymous> (C:\Users\xdswe\Desktop\Zero\src\Structures\MenuDocsClient.js:38:13)
    at MenuDocsClient.emit (events.js:311:20)
    at MessageCreateAction.handle (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:311:20)