问:
Spring Boot : Multi-layered @Services in RESTful controllers for many inbound requests
Not sure if this is a code review or questions on how Spring Boot operates regarding @Service components with many inbound requests.  If it is a question I can certainly re-post in StackExchange > Code Reviews?  We basically have the following pattern in Spring Boot :

Spring Boot application

RESTful controllers that process List<DocumentMetadata> objects

RESTful controller uses a Data Management @Service to handle fetching and sorting of ocumentMetadata objects

Data Management @Service uses a Custom sorting @Service to do the sorting of these documentMetadata objects

Narrative : Essentially a RESTful endpoint will return a List<DocumentMetadata> objects (List of objects if you will) as a ResponseEntity.  The custom sorting is implemented as an @Service with a method for the sort().  My understanding is that Spring Boot will create a "singleton" instance of the Custom sorting @Service utility.  I've googled a number of questions on Spring Boot @Service and lifecycle, and found the following.  This posting, which described some usage that led to my questions/review, Should service layer classes be singletons? , especially this comment "Also, mutable state within a Spring singleton is absolutely fine, you just need to be aware of what operations can be done on that shared state – skaffman".  I also read thru this posting, Can Spring Boot application handle multiple requests simultaneously?, which seems to suggest we are ok since the object we are creating, sorting and returning is created within the @GetMapping and passed into the Service component layers, i.e. it's not shared.

My Questions :

Is this even the right way to design a RESTful stack?  Specifically the Utility classes we need...should they be done as @Service or as POJO classes that get used within the Data Management @Service layer.

In a multi-request situation where 10-100 requests are hitting the RESTful endpoint at once, what happens to the Custom Sorting utility @Service and the sort() method?  Does the sort() method service each request sequentially? or in parallel in different threads?

Is every request using the same sort method, i.e. the Custom Sorting utility @Service is a "singleton" so how is the sort() method utilized?

If the sort() method is truly single, could 1 user potentially end up with another user's sorted List if both Users hit the method simultaneously?  Or does Spring Boot simply process the inbound requests in sequence or in their own threads and avoid any mixing.

Code snippets : I removed much of the code for brevity.

```<code>@RestController
@RequestMapping(value = "/search")
@CrossOrigin(origins = "*")
@Slf4j
public class SearchController {

    // @Service for Data handling...
    @Autowired
    private DataManagementService dataManagementService;

    @GetMapping(value="/viewable-documents")
    public SearchResponse getExternallyViewableDocuments(@RequestParam(required = false) Map<String, String> queryParams) {
        logger.debug("getViewableDocuments is called with {}", queryParams);

        SearchResponse searchResponse = new SearchResponse();

        // ENDPOINT : Calls the Data Management handling @Service...
        SearchResponse response = dataManagementService.getDocuments(queryParams);

    }
}

@Service
public class DataManagementServiceImpl implements DataManagementService {

    // CUSTOM SORT UTILITY : Autowired with setter...
    private DocumentSortUtility documentSortUtility;

    @Autowired
    public void setDocumentSortUtility(DocumentSortUtility setValue) {
        this.documentSortUtility = setValue;
    }

    @Override
    public SearchResponse getDocuments(Map<String, String> request) {

        if (request.get("sort") != null && request.get("sort").equals("true")) {

            // SORT : Call the custom sort...
            return serviceImpl.populateResponse(this.documentSortUtility.sort(response));

        } else {
            return serviceImpl.populateResponse(response);
        }
    }
}

@Service
public class DocumentSortUtility {

    public List<DocumentMetadata> sort(List<DocumentMetadata> documentMetadataList) {
        log.debug("Un Sorted:"+documentMetadataList);

        // Do custom sort of documentMetadataList and place in retList...

        log.debug("Sorted:"+retList);
        return retList;
    }
}
</code>```

I have confirmed in the code that there are no "shared" mutable objects being maintained/managed in the @Service layers.  The only objects being modified and/or created are done within the methods of the @Service layers.

Thx in advance...

答:
As I can see, your confusion based on the Spring's Singleton scope and how Spring handles multiple requests when @Service classes are being Singleton.

Spring create and bind beans as Singleton objects unless you define particular scope using @Scope annotation or annotation respective to the scope, like @SessionScope. You may already know about this.

If you have fuzz about Singleton objects on multiple threads, this answer provides excellent explanation. So, about your questions;

Is this even the right way to design a RESTful stack? Specifically the
  Utility classes we need, should they be done as @Service or as
  POJO classes that get used within the Data Management @Service
  layer?

Yes and no. This is the right way if your @Service class is singleton (it must be) and immutable (Stateless). Which means, your @Service class should not have any modifiable field. Otherwise, your @Service would lead to unpredictable results.

If a POJO's been used in this context, object instantiation would initialize new object each time when a new thread started, which brings us to your second question;

In a multi-request situation where 10-100 requests are hitting the
  RESTful endpoint at once, what happens to the Custom Sorting utility
  @Service and the sort() method? Does the sort() method service each
  request sequentially? or in parallel in different threads?

When 10-100 or thousands or requests hit on the endpoint, if you have used a POJO, it also create thousands of additional objects which pollute the heap unnecessarily since we can use one singleton object using @Service annotation. Since the, singleton object is immutable (which wouldn't keep any change by its method invocations) and shared between multiple thread, capable to execute simultaneously without any side effect on the result.

If the sort() happens in memory and return the sorted results afterward, it executes independently wrapped in thread's execution.

Is every request using the same sort method, i.e. the Custom Sorting
  utility @Service is a "singleton" so how is the sort() method
  utilized?

Singleton doesn't mean that its functions cannot be shared unless they are specifically synchronized. In your case, I believe this sort() method is not synchronized. So, there's no problem to execute sort() method on each of the thread separately (no discrepancies as our singleton object is stateless/immutable).

If the sort() method is truly single, could 1 user potentially end up
  with another user's sorted List if both Users hit the method
  simultaneously? Or does Spring Boot simply process the inbound
  requests in sequence or in their own threads and avoid any mixing.

You know, that Spring boot is based on Java EE. So, basically it uses a javax.servlet.ServletContext class instances to handle this request and response flow and whole lot of other classes from Java EE involves in this process which we can't see due Spring's clever design. But the flow is the same. In a nutshell, each request has separate thread bound to it and those request-threads never gets mixed up whatsoever. That thread involves the whole process until response is dispatched to the client.

Have you ever notice, we don't create thread manually except for special scenarios? That because, Java EE ecosystems manage these threads behalf of us.

So, answer to your question is, no, sort() would not execute once and never ever one request's results end up in other request's response object, no matter how many thousand users make the request simultaneously. This answer also provide brilliant explanation about how these request - response mechanism work underneath.

Body:
Not sure if this is a code review or questions on how Spring Boot operates regarding @Service components with many inbound requests.  If it is a question I can certainly re-post in StackExchange > Code Reviews?  We basically have the following pattern in Spring Boot :

Spring Boot application

RESTful controllers that process List<DocumentMetadata> objects

RESTful controller uses a Data Management @Service to handle fetching and sorting of ocumentMetadata objects

Data Management @Service uses a Custom sorting @Service to do the sorting of these documentMetadata objects

Narrative : Essentially a RESTful endpoint will return a List<DocumentMetadata> objects (List of objects if you will) as a ResponseEntity.  The custom sorting is implemented as an @Service with a method for the sort().  My understanding is that Spring Boot will create a "singleton" instance of the Custom sorting @Service utility.  I've googled a number of questions on Spring Boot @Service and lifecycle, and found the following.  This posting, which described some usage that led to my questions/review, Should service layer classes be singletons? , especially this comment "Also, mutable state within a Spring singleton is absolutely fine, you just need to be aware of what operations can be done on that shared state – skaffman".  I also read thru this posting, Can Spring Boot application handle multiple requests simultaneously?, which seems to suggest we are ok since the object we are creating, sorting and returning is created within the @GetMapping and passed into the Service component layers, i.e. it's not shared.

My Questions :

Is this even the right way to design a RESTful stack?  Specifically the Utility classes we need...should they be done as @Service or as POJO classes that get used within the Data Management @Service layer.

In a multi-request situation where 10-100 requests are hitting the RESTful endpoint at once, what happens to the Custom Sorting utility @Service and the sort() method?  Does the sort() method service each request sequentially? or in parallel in different threads?

Is every request using the same sort method, i.e. the Custom Sorting utility @Service is a "singleton" so how is the sort() method utilized?

If the sort() method is truly single, could 1 user potentially end up with another user's sorted List if both Users hit the method simultaneously?  Or does Spring Boot simply process the inbound requests in sequence or in their own threads and avoid any mixing.

Code snippets : I removed much of the code for brevity.

@RestController
@RequestMapping(value = "/search")
@CrossOrigin(origins = "*")
@Slf4j
public class SearchController {

    // @Service for Data handling...
    @Autowired
    private DataManagementService dataManagementService;

    @GetMapping(value="/viewable-documents")
    public SearchResponse getExternallyViewableDocuments(@RequestParam(required = false) Map<String, String> queryParams) {
        logger.debug("getViewableDocuments is called with {}", queryParams);

        SearchResponse searchResponse = new SearchResponse();

        // ENDPOINT : Calls the Data Management handling @Service...
        SearchResponse response = dataManagementService.getDocuments(queryParams);

    }
}

@Service
public class DataManagementServiceImpl implements DataManagementService {

    // CUSTOM SORT UTILITY : Autowired with setter...
    private DocumentSortUtility documentSortUtility;

    @Autowired
    public void setDocumentSortUtility(DocumentSortUtility setValue) {
        this.documentSortUtility = setValue;
    }

    @Override
    public SearchResponse getDocuments(Map<String, String> request) {

        if (request.get("sort") != null && request.get("sort").equals("true")) {

            // SORT : Call the custom sort...
            return serviceImpl.populateResponse(this.documentSortUtility.sort(response));

        } else {
            return serviceImpl.populateResponse(response);
        }
    }
}

@Service
public class DocumentSortUtility {

    public List<DocumentMetadata> sort(List<DocumentMetadata> documentMetadataList) {
        log.debug("Un Sorted:"+documentMetadataList);

        // Do custom sort of documentMetadataList and place in retList...

        log.debug("Sorted:"+retList);
        return retList;
    }
}

I have confirmed in the code that there are no "shared" mutable objects being maintained/managed in the @Service layers.  The only objects being modified and/or created are done within the methods of the @Service layers.

Thx in advance...


来源: stackexchange

问:
How to group and calculate in pandas
I have df like below

```<code>customer class  score
A          a      10
A          b      20
B          a      40
B          b      50
</code>```

I would like to group, transform and calculate like this.

```<code>customer  score(b-a)
A           10
B           10
</code>```

I couldnt figure out how to calculate..

```<code>df.groupby(df.customer)
</code>```

If someone has experienced such aggregation,please let me know.

Thanks

答:
You can use @HenryYik's comment, or you can use pivot:

```<code>(df.pivot(index='customer', columns='class', values='score')
   .assign(score=lambda x: x['b']-x['a'])
)
</code>```

Output:

```<code>class      a   b  score
customer
A         10  20     10
B         40  50     10
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to group and calculate in pandas

Body:
I have df like below

customer class  score
A          a      10
A          b      20
B          a      40
B          b      50

I would like to group, transform and calculate like this.

customer  score(b-a)
A           10
B           10

I couldnt figure out how to calculate..

df.groupby(df.customer)

If someone has experienced such aggregation,please let me know.

Thanks

Body:
You can use @HenryYik's comment, or you can use pivot:

(df.pivot(index='customer', columns='class', values='score')
   .assign(score=lambda x: x['b']-x['a'])
)

Output:

class      a   b  score
customer
A         10  20     10
B         40  50     10


问:
Are there any performance issues when running Solr on Windows OS
I wanted to ask if there are any known performance/instability issues when running Solr on Windows OS (Windows Server 2016)? We plan to run in cloud mode, so that would mean also running zookeeper on Windows as well.

The environment where Solr is to be added is 100% Windows and it is what the team knows, so if there are no adverse reasons it would be preferable run on that OS for the search solution as well.

Hopefully this question isn't too open-ended for this forum; if it is and there is a better place to ask it, i can move it.

Thanks,

答:
I am running the solr on Windows OS and did not face any issues till now.
I am using the solrCloud feature, it also requires the Zookeeper running.

But all this is running on the development environment.

I never used the same on production environment. Its always preferred to have Unix/Linux environment and solr is running on top of it.

My system is having 8GB of RAM and rest all works fine along with running solr.
My Collection has 1 Millions of records currently.


问:
query sql SUM only 1 value on duplicate value with JOIN
I have problem again with query of sql.

I have 2 table. 'transactions' table and 'transactaion_detail' tabel.

transactions as trx

```<code>ID    TOTAL
1     2000
2     10000
3     5000
</code>```

transactions_details as td

```<code>ID    trx_id     PRICE
1       1        2000
2       2        5000
3       2        5000
4       3        1000
5       3        2000
6       3        2000
</code>```

when I query like this

```<code>select sum(trx.total) from transactions as trx
join transaction_details as td
on trx.id = td.trx_id
</code>```

I got result

37000

thats result that is not what I meant.

because when I change sum(trx.total) to trx.*

the data show like this

```<code>ID    TOTAL
1     2000
2     10000
2     10000
3     5000
3     5000
3     5000
</code>```

I want get result 17000 from that query.

I know I can just sum price on table transaction_detail or sum total on transcations without join another table. but in my case I have to join 2 table and SUM.

please help me

答:
You are missing GROUP BY , change your query like following.

```<code>SELECT trx.id
    ,sum(trx.total)
FROM transactions AS trx
JOIN transaction_details AS td ON trx.id = td.trx_id
GROUP BY trx.id
</code>```

Body:
I have problem again with query of sql.

I have 2 table. 'transactions' table and 'transactaion_detail' tabel.

transactions as trx

ID    TOTAL
1     2000
2     10000
3     5000

transactions_details as td

ID    trx_id     PRICE
1       1        2000
2       2        5000
3       2        5000
4       3        1000
5       3        2000
6       3        2000

when I query like this

select sum(trx.total) from transactions as trx
join transaction_details as td
on trx.id = td.trx_id

I got result

37000

thats result that is not what I meant.

because when I change sum(trx.total) to trx.*

the data show like this

ID    TOTAL
1     2000
2     10000
2     10000
3     5000
3     5000
3     5000

I want get result 17000 from that query.

I know I can just sum price on table transaction_detail or sum total on transcations without join another table. but in my case I have to join 2 table and SUM.

please help me

Body:
You are missing GROUP BY , change your query like following.

SELECT trx.id
    ,sum(trx.total)
FROM transactions AS trx
JOIN transaction_details AS td ON trx.id = td.trx_id
GROUP BY trx.id


问:
Get total [checkbox] value
HTML:

```<code><input type="checkbox" name="product[book]" value="10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane
</code>```

PHP:

```
<code>
foreach ($_POST['product'] as $name => $value) {
    echo $value;
}
</code>
```

How to get the total (sum) value if the user select two fields (book & plane)

答:
try</p>

```<code>   $total=0;
   foreach ($_POST['product'] as $k) {
    $total +=$k;
}
echo $total;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get total [checkbox] value

Body:
HTML:

<input type="checkbox" name="product[book]" value="10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane

PHP:

foreach ($_POST['product'] as $name => $value) {
    echo $value;
}

How to get the total (sum) value if the user select two fields (book & plane)

Body:
try

   $total=0;
   foreach ($_POST['product'] as $k) {
    $total +=$k;
}
echo $total;


问:
checking for at least 1 number between 0-9 in a given password using c#
I'm trying to cycle through each char in a string to see if any of them are a number between 0-9. I'm getting an index out of bounds error for the numCheck array, so I know that my issue is that when I attempt to run, the IDE expects the length of txt_Pass.Text to = the number of chars I have in my array. This is wrong, but I'm not sure how to fix it. Would I need to use a vector since I'm not sure how long the input password will be? Or am I totally off?

```<code>        char[] numCheck = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        for (int i = 0; i < txt_Pass.Text.Length; i++)
        {
            if (txt_Pass.Text[i] != numCheck[i])
            {
                lbl_Form1_NumError.Visible = true;
            }
            lbl_Form1_NumError.Visible = false;
        }
</code>```

'''

答:
LINQ to the rescue!

```<code>var numCheck = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
lbl_Form1_NumError.Visible = txt_Pass.Text.Any(c => numCheck.Contains(c));
</code>```

Regex to the rescue!

```<code>using System.Text.RegularExpressions;

lbl_Form1_NumError.Visible = Regex.IsMatch(txt_Pass.Text, @"\d")
</code>```

Body:
I'm trying to cycle through each char in a string to see if any of them are a number between 0-9. I'm getting an index out of bounds error for the numCheck array, so I know that my issue is that when I attempt to run, the IDE expects the length of txt_Pass.Text to = the number of chars I have in my array. This is wrong, but I'm not sure how to fix it. Would I need to use a vector since I'm not sure how long the input password will be? Or am I totally off?

        char[] numCheck = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        for (int i = 0; i < txt_Pass.Text.Length; i++)
        {
            if (txt_Pass.Text[i] != numCheck[i])
            {
                lbl_Form1_NumError.Visible = true;
            }
            lbl_Form1_NumError.Visible = false;
        }

'''

Body:
LINQ to the rescue!

var numCheck = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
lbl_Form1_NumError.Visible = txt_Pass.Text.Any(c => numCheck.Contains(c));

Regex to the rescue!

using System.Text.RegularExpressions;

lbl_Form1_NumError.Visible = Regex.IsMatch(txt_Pass.Text, @"\d")


问:
Reset work node when to rejoin to master using kubeadm
When I drain and remove existing work node in cluster, if I want to rejoin it to master, it report a error under below.</p>

```<code>error execution phase preflight: [preflight] Some fatal errors occurred:
  [ERROR FileAvailable--etc-kubernetes-kubelet.conf]: /etc/kubernetes/kubelet.conf already exists
  [ERROR FileAvailable--etc-kubernetes-pki-ca.crt]: /etc/kubernetes/pki/ca.crt already exists
</code>```

答:
It is happening because you've already executed join command on your node once. That's why the files are still there.

If your node hasn't been deleted from the cluster(just drained only), you don't have to run kubeadm join. You can rejoin the node by running the command-

```<code>kubectl uncordon NODENAME
</code>```

Else, to get rid of this error, try running the following command on your node to purge these files-

```<code>kubeadm reset
</code>```

If the reset command fails, try forcing the reset process by running-

```<code>kubeadm reset --force
</code>```

Now try to execute the join command again.

Body:
When I drain and remove existing work node in cluster, if I want to rejoin it to master, it report a error under below.

error execution phase preflight: [preflight] Some fatal errors occurred:
  [ERROR FileAvailable--etc-kubernetes-kubelet.conf]: /etc/kubernetes/kubelet.conf already exists
  [ERROR FileAvailable--etc-kubernetes-pki-ca.crt]: /etc/kubernetes/pki/ca.crt already exists

Body:
It is happening because you've already executed join command on your node once. That's why the files are still there.

If your node hasn't been deleted from the cluster(just drained only), you don't have to run kubeadm join. You can rejoin the node by running the command-

kubectl uncordon NODENAME

Else, to get rid of this error, try running the following command on your node to purge these files-

kubeadm reset

If the reset command fails, try forcing the reset process by running-

kubeadm reset --force

Now try to execute the join command again.


问:
R: How can I compute number of occurrences and average delta times for unique column-column matches in a dataframe
I have a dataset that represents patients visits to various doctors in a certain practice throughout a year.

Example-

```<code>doctor    patient_no  datetime

dr.kahn   1561        1/21/19 10:30:00
dr.gould  1397        2/06/19 12:30:00
dr.amoor  1596        2/11/19 9:00:00
dr.gould  995         10/07/19 12:30:00
dr.kahn   1561        10/14/19 9:30
</code>```

I'm trying to create a new dataframe where each row is a unique doctor-patient pairing
and shows the numbers of times that patient visited that doctor, along with the average time surpassed between visits for that particular patient-doctor pairing.  So for instance if patient A went to dr.kahn 4 times in a year, what was the average amount of time in between patient A's consecutive appointments to dr.kahn.

Example-

```<code>doctor   patient_no   number_of_visits  avg_time_passed_between_appointments

dr.gould   1054       7                 2 months 1 days  2:00:00
dr.gould   1099       2                 5 months 10 days 00:00:00
dr.kahn    875        12                0 months 26 days 0:30:00
</code>```

Any help would be appreciated.  Thanks!

答:
Here's a dplyr approach:

```<code>library(tidyverse)
df %>%
  mutate(datetime = lubridate::mdy_hm(datetime)) %>%
  group_by(doctor, patient_no) %>%
  summarize(count = n(),
            avg_days_between = (max(datetime) - min(datetime)) / lubridate::ddays(count - 1)) %>%
  ungroup()

## A tibble: 4 x 4
#  doctor   patient_no count avg_days_between
#  <chr>         <dbl> <int>            <dbl>
#1 dr.amoor       1596     1             NaN
#2 dr.gould        995     1             NaN
#3 dr.gould       1397     1             NaN
#4 dr.kahn        1561     2             266.
</code>```

Or you could calculate each lag and use a different method, like the median, to characterize avg delta.

```<code>df %>%
  group_by(doctor, patient_no) %>%
  mutate(datetime = lubridate::mdy_hm(datetime),
         # coalesce helps
         days_since_last = coalesce(c(datetime - lag(datetime))/
                                      lubridate::ddays(1), 0)) %>%
  summarize(count = n(),
            median_time_between = median(days_since_last))

## A tibble: 4 x 4
# Groups:   doctor [3]
#  doctor   patient_no count median_time_between
#  <chr>         <dbl> <int>               <dbl>
#1 dr.amoor       1596     1                  0
#2 dr.gould        995     1                  0
#3 dr.gould       1397     1                  0
#4 dr.kahn        1561     2                133.
</code>```

sample data

```<code>df <- tibble::tribble(
     ~doctor, ~patient_no,       ~datetime,
   "dr.kahn",        1561, "1/21/19 10:30",
  "dr.gould",        1397,  "2/6/19 12:30",
  "dr.amoor",        1596,  "2/11/19 9:00",
  "dr.gould",         995, "10/7/19 12:30",
   "dr.kahn",        1561, "10/14/19 9:30"
  )
</code>```

Body:
I have a dataset that represents patients visits to various doctors in a certain practice throughout a year.

Example-

doctor    patient_no  datetime

dr.kahn   1561        1/21/19 10:30:00
dr.gould  1397        2/06/19 12:30:00
dr.amoor  1596        2/11/19 9:00:00
dr.gould  995         10/07/19 12:30:00
dr.kahn   1561        10/14/19 9:30

I'm trying to create a new dataframe where each row is a unique doctor-patient pairing
and shows the numbers of times that patient visited that doctor, along with the average time surpassed between visits for that particular patient-doctor pairing.  So for instance if patient A went to dr.kahn 4 times in a year, what was the average amount of time in between patient A's consecutive appointments to dr.kahn.

Example-

doctor   patient_no   number_of_visits  avg_time_passed_between_appointments

dr.gould   1054       7                 2 months 1 days  2:00:00
dr.gould   1099       2                 5 months 10 days 00:00:00
dr.kahn    875        12                0 months 26 days 0:30:00

Any help would be appreciated.  Thanks!

Body:
Here's a dplyr approach:

library(tidyverse)
df %>%
  mutate(datetime = lubridate::mdy_hm(datetime)) %>%
  group_by(doctor, patient_no) %>%
  summarize(count = n(),
            avg_days_between = (max(datetime) - min(datetime)) / lubridate::ddays(count - 1)) %>%
  ungroup()

## A tibble: 4 x 4
#  doctor   patient_no count avg_days_between
#  <chr>         <dbl> <int>            <dbl>
#1 dr.amoor       1596     1             NaN
#2 dr.gould        995     1             NaN
#3 dr.gould       1397     1             NaN
#4 dr.kahn        1561     2             266.

Or you could calculate each lag and use a different method, like the median, to characterize avg delta.

df %>%
  group_by(doctor, patient_no) %>%
  mutate(datetime = lubridate::mdy_hm(datetime),
         # coalesce helps
         days_since_last = coalesce(c(datetime - lag(datetime))/
                                      lubridate::ddays(1), 0)) %>%
  summarize(count = n(),
            median_time_between = median(days_since_last))

## A tibble: 4 x 4
# Groups:   doctor [3]
#  doctor   patient_no count median_time_between
#  <chr>         <dbl> <int>               <dbl>
#1 dr.amoor       1596     1                  0
#2 dr.gould        995     1                  0
#3 dr.gould       1397     1                  0
#4 dr.kahn        1561     2                133.

sample data

df <- tibble::tribble(
     ~doctor, ~patient_no,       ~datetime,
   "dr.kahn",        1561, "1/21/19 10:30",
  "dr.gould",        1397,  "2/6/19 12:30",
  "dr.amoor",        1596,  "2/11/19 9:00",
  "dr.gould",         995, "10/7/19 12:30",
   "dr.kahn",        1561, "10/14/19 9:30"
  )


问:
Search Between can hide the past product_Name transaction
//this is my for loop</p>

```<code>DefaultTableModel model =(DefaultTableModel)inventory_Table.getModel();
Object[] row = new Object[12];

for(int i = 0; i < Listass.size(); i++) {
    row[1] = Listass.get(i).getType();
    row[2] = Listass.get(i).getProduct();
    row[3] = Listass.get(i).getPacking();
    row[4] = Listass.get(i).getQuantity();
    row[5] = Listass.get(i).getAmount();
    row[6] = Listass.get(i).getSupplier();
    row[7] = Listass.get(i).getPONumber();
    row[8] = Listass.get(i).getUnitPrice();
    row[9] = Listass.get(i).getTDR();
    row[10] = Listass.get(i).getSDR();
    row[0] = Listass.get(i).getDate();
    row[11] = Listass.get(i).getProductNumber();
    model.addRow(row);
}
</code>```

答:
Consider the lines:

```<code>Object[] row = new Object[12];
for(int i = 0; i < Listass.size(); i++) {
    ...
    model.addRow(row);
}
</code>```

You only assign 1 value to row (the new array). So you are actually adding the same array reference multiple times to the model. addRow doesn't copy the data in the array - it just stores a reference to it to represent the data in the row. Subsequent iterations override that data so all rows end up showing the final values.

The solution is to create a new array inside the loop:

```<code>for(int i = 0; i < Listass.size(); i++) {
    Object[] row = new Object[12];
    ...
    model.addRow(row);
}
</code>```

Now each row points to a different array.

Be aware that there are several stylist issues with the code you posted. I haven't corrected any of those here but you should read a Java style guide and try to conform to expected standards in the industry.

Body:
//this is my for loop

DefaultTableModel model =(DefaultTableModel)inventory_Table.getModel();
Object[] row = new Object[12];

for(int i = 0; i < Listass.size(); i++) {
    row[1] = Listass.get(i).getType();
    row[2] = Listass.get(i).getProduct();
    row[3] = Listass.get(i).getPacking();
    row[4] = Listass.get(i).getQuantity();
    row[5] = Listass.get(i).getAmount();
    row[6] = Listass.get(i).getSupplier();
    row[7] = Listass.get(i).getPONumber();
    row[8] = Listass.get(i).getUnitPrice();
    row[9] = Listass.get(i).getTDR();
    row[10] = Listass.get(i).getSDR();
    row[0] = Listass.get(i).getDate();
    row[11] = Listass.get(i).getProductNumber();
    model.addRow(row);
}

Body:
Consider the lines:

Object[] row = new Object[12];
for(int i = 0; i < Listass.size(); i++) {
    ...
    model.addRow(row);
}

You only assign 1 value to row (the new array). So you are actually adding the same array reference multiple times to the model. addRow doesn't copy the data in the array - it just stores a reference to it to represent the data in the row. Subsequent iterations override that data so all rows end up showing the final values.

The solution is to create a new array inside the loop:

for(int i = 0; i < Listass.size(); i++) {
    Object[] row = new Object[12];
    ...
    model.addRow(row);
}

Now each row points to a different array.

Be aware that there are several stylist issues with the code you posted. I haven't corrected any of those here but you should read a Java style guide and try to conform to expected standards in the industry.


问:
Best free Java profiler on Mac
I was using YourKit before and it was working perfectly, but it's too expensive for my taste. Is there some free or open-source Java profiler for Mac that's working as well as YourKit?</p>

Title: Best free Java profiler on Mac


答:
Alternative solution, group by over customer and apply a custom function

```<code>def get_score(temp):
    map_score = dict(zip(temp['class'], temp['score'])) # mapping of class and score for each customer
    return map_score['b'] - map_score['a']
df.groupby("customer").apply(get_score)
</code>```

This will result in expected answer.

Title: How to group and calculate in pandas

Body:
Alternative solution, group by over customer and apply a custom function

def get_score(temp):
    map_score = dict(zip(temp['class'], temp['score'])) # mapping of class and score for each customer
    return map_score['b'] - map_score['a']
df.groupby("customer").apply(get_score)

This will result in expected answer.


问:
ScheduledExecutorService inside a Spring Bean, not working after a couple of executions
I am trying to schedule a task inside a Spring @Bean which will update the property of the instance returning from Bean.

I am able to run this code, and the executor works fine a couple of times, but after that, it suddenly stops loading.

What exactly is the problem here? Is there a better way to work this out??

```<code>@Bean(name="service")
public Service getService(){
  Service service = new Service();
  ScheduledExecutorService serviceLoader = Executors.newScheduledThreadPool(1);
    serviceLoader.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            service.loadAllLiveEvents();
        }
    }, 0, 1, TimeUnit.HOURS);

  return service;
}
</code>```

答:
The lifecycle of serviceLoader looks weird - it gets initialized right during the method or service, then schedules some work and then service gets returned. What happens to the reference to this pool? when the shutdown can be called?

In addition, the first iteration runs immediately, and this happens when the application context is not ready yet, this can lead to unpredictable results depending on the actual code that runs during the iteration.

I can't say for sure what happens based on this code snippet, but here are some possible solutions:

Use @Scheduled annotation, running scheduled tasks is a bulit-in spring feature. There are a lot of tutorials, here is one of them

If you absolutely have to use the thread pool, I suggest the following configuration:

```<code>@Configuration
public class MyConfiguration {
   @Bean
   public Service service() {
      return new Service();
   }
   @Bean(destroyMethod="shutdownNow") // or shutdown - now spring will close the pool when the app context gets closed
   @Qualifier("serviceLoaderPool")
   public ScheduledExecutorService serviceLoader() {
        return Executors.newScheduledThreadPool(1);
   }

   @EventListener
   public void onAppContextStarted(ApplicationReadyEvent evt) {
       ScheduledExecutorService loader =
       (ScheduledExecutorService)evt.getApplicationContext().getBean("serviceLoaderPool");
       Service service = evt.getApplicationContext.getBean(Service.class);
       loader.scheduleAtFixedRate(new Runnable() {
           @Override
           public void run() {
               service.loadAllLiveEvents();
           }
       }, 0, 1, TimeUnit.HOURS);
   }
}
</code>```

With this approach you can be sure that the service will start refreshing when the application context is ready.

The lifecycle of the executor service is well-defined as well, spring manages it as a regular singleton bean, so it won't be GC'ed as long as the application context is up-and-running.

The presence of destroy method guarantees graceful shutdown (again, spring will call it for you).

Body:
I am trying to schedule a task inside a Spring @Bean which will update the property of the instance returning from Bean.

I am able to run this code, and the executor works fine a couple of times, but after that, it suddenly stops loading.

What exactly is the problem here? Is there a better way to work this out??

@Bean(name="service")
public Service getService(){
  Service service = new Service();
  ScheduledExecutorService serviceLoader = Executors.newScheduledThreadPool(1);
    serviceLoader.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            service.loadAllLiveEvents();
        }
    }, 0, 1, TimeUnit.HOURS);

  return service;
}

Body:
The lifecycle of serviceLoader looks weird - it gets initialized right during the method or service, then schedules some work and then service gets returned. What happens to the reference to this pool? when the shutdown can be called?

In addition, the first iteration runs immediately, and this happens when the application context is not ready yet, this can lead to unpredictable results depending on the actual code that runs during the iteration.

I can't say for sure what happens based on this code snippet, but here are some possible solutions:

Use @Scheduled annotation, running scheduled tasks is a bulit-in spring feature. There are a lot of tutorials, here is one of them

If you absolutely have to use the thread pool, I suggest the following configuration:

@Configuration
public class MyConfiguration {
   @Bean
   public Service service() {
      return new Service();
   }
   @Bean(destroyMethod="shutdownNow") // or shutdown - now spring will close the pool when the app context gets closed
   @Qualifier("serviceLoaderPool")
   public ScheduledExecutorService serviceLoader() {
        return Executors.newScheduledThreadPool(1);
   }

   @EventListener
   public void onAppContextStarted(ApplicationReadyEvent evt) {
       ScheduledExecutorService loader =
       (ScheduledExecutorService)evt.getApplicationContext().getBean("serviceLoaderPool");
       Service service = evt.getApplicationContext.getBean(Service.class);
       loader.scheduleAtFixedRate(new Runnable() {
           @Override
           public void run() {
               service.loadAllLiveEvents();
           }
       }, 0, 1, TimeUnit.HOURS);
   }
}

With this approach you can be sure that the service will start refreshing when the application context is ready.

The lifecycle of the executor service is well-defined as well, spring manages it as a regular singleton bean, so it won't be GC'ed as long as the application context is up-and-running.

The presence of destroy method guarantees graceful shutdown (again, spring will call it for you).


问:
How to make Widget not overflow ListView on Flutter Web
Context: I'm trying to make a web app with Flutter - so this is all in Chrome

Problem: I have a chart, from the charts_flutter library, and it renders OK when inside a Column. The issue is that I want to be able to scroll and add more content below the chart. When I try changing the column to a ListView, it overflows (seems the Chart is trying to be as big as possible and the ListView has infinite height). I'm not sure how to get around this issue.

Current Code:
Just the scaffold, because that's all that I think is important here

```<code>Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: ListView(
        children: <Widget>[
          Row(
            children: <Widget>[
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 1")),
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 2")),
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 3")),
            ],
            mainAxisAlignment: MainAxisAlignment.center,
          ),
          Flexible(child: GroupedStackedBarChart.withRandomData()),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
</code>```

答:
buddy just wraps your Listview with Expanded and Expand your widget with Column like this:

```<code>body: Column(
        children: <Widget>[
          Expanded(
            child: ListView(
              children: <Widget>[

              ],
            ),
          ),
</code>```

Body:
Context: I'm trying to make a web app with Flutter - so this is all in Chrome

Problem: I have a chart, from the charts_flutter library, and it renders OK when inside a Column. The issue is that I want to be able to scroll and add more content below the chart. When I try changing the column to a ListView, it overflows (seems the Chart is trying to be as big as possible and the ListView has infinite height). I'm not sure how to get around this issue.

Current Code:
Just the scaffold, because that's all that I think is important here

Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: ListView(
        children: <Widget>[
          Row(
            children: <Widget>[
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 1")),
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 2")),
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 3")),
            ],
            mainAxisAlignment: MainAxisAlignment.center,
          ),
          Flexible(child: GroupedStackedBarChart.withRandomData()),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );

Body:
buddy just wraps your Listview with Expanded and Expand your widget with Column like this:

body: Column(
        children: <Widget>[
          Expanded(
            child: ListView(
              children: <Widget>[

              ],
            ),
          ),


问:
Flutter Webview Google OAuth
I have a Flutter app that's leveraging a Webview. The location of this Webview is an external site that supports Google auth, which is failing due to a 403 disalowed_useragent. I know that Google no longer supports OAuth requests using embedded browsers, but does anyone know of a workaround?</p>

```<code>class CheckOutExternalPage extends StatefulWidget {
  final String url;

  CheckOutExternalPage({Key key, this.url}) : super(key: key);

  @override
  _CheckOutExternalPageState createState() => _CheckOutExternalPageState();
}

class _CheckOutExternalPageState extends State<CheckOutExternalPage> {
  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      geolocationEnabled: true,
      withZoom: true,
      withLocalStorage: true,
      withJavascript: true,
      supportMultipleWindows: true,
      url: widget.url,
      appBar: new AppBar(
        title: const Text('Check Out'),
      ),
    );
  }
}
</code>```

答:
Read Api at https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebView/userAgent.html

so you have to use something like

```<code>String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36";
</code>```

and then webview.userAgent=useragent ;

Title: Flutter Webview Google OAuth

Body:
I have a Flutter app that's leveraging a Webview. The location of this Webview is an external site that supports Google auth, which is failing due to a 403 disalowed_useragent. I know that Google no longer supports OAuth requests using embedded browsers, but does anyone know of a workaround?

class CheckOutExternalPage extends StatefulWidget {
  final String url;

  CheckOutExternalPage({Key key, this.url}) : super(key: key);

  @override
  _CheckOutExternalPageState createState() => _CheckOutExternalPageState();
}

class _CheckOutExternalPageState extends State<CheckOutExternalPage> {
  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      geolocationEnabled: true,
      withZoom: true,
      withLocalStorage: true,
      withJavascript: true,
      supportMultipleWindows: true,
      url: widget.url,
      appBar: new AppBar(
        title: const Text('Check Out'),
      ),
    );
  }
}

Body:
Read Api at https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebView/userAgent.html

so you have to use something like

String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36";

and then webview.userAgent=useragent ;


问:
Here.com API proper structure
When I run this code:

```<code>url = f"https://traffic.ls.hereapi.com//traffic/6.3/incidents.json?proximity=37.3541,-121.9552?apiKey={api_key}"

Scrape Here.com for any traffic incidents in the last 24 hours for the set proximity
res = requests.get(url)
date_requested = time.strftime('%Y-%m-%d')
time_requested = time.strftime('%H:%M')
date_requested; time_requested #print date & time of request
</code>```

I get this error:

```<code><html><body><p>{"error":"Unauthorized","error_description":"ApiKey is missing."}</p></body></html>
</code>```

Can anyone tell me why?  I know the API key is valid because I generated a new one and cut and pasted it into the code above so it has to be the structure of my query, no?

I would really appreciate any and all help.

答:
Problem is in your URL part replace second ? with & as below-

```<code>url = f"https://traffic.ls.hereapi.com//traffic/6.3/incidents.json?proximity=37.3541,-121.9552&apiKey={}"
</code>```

Title: Here.com API proper structure

Body:
When I run this code:

url = f"https://traffic.ls.hereapi.com//traffic/6.3/incidents.json?proximity=37.3541,-121.9552?apiKey={api_key}"

Scrape Here.com for any traffic incidents in the last 24 hours for the set proximity
res = requests.get(url)
date_requested = time.strftime('%Y-%m-%d')
time_requested = time.strftime('%H:%M')
date_requested; time_requested #print date & time of request

I get this error:

{"error":"Unauthorized","error_description":"ApiKey is missing."}

Can anyone tell me why?  I know the API key is valid because I generated a new one and cut and pasted it into the code above so it has to be the structure of my query, no?

I would really appreciate any and all help.

Body:
Problem is in your URL part replace second ? with & as below-

url = f"https://traffic.ls.hereapi.com//traffic/6.3/incidents.json?proximity=37.3541,-121.9552&apiKey={}"


问:
How to update all of my dotnet global tool by one command
I install too many dotnet tool but how to keey they in lastest version. I do not want to update them manual.

I find the github issus: Add dotnet tool update --all option · Issue #10130 · dotnet/sdk

答:
I write a tool that can update all dotnet tool

Installation

```<code>dotnet tool install --global dotnetCampus.UpdateAllDotNetTools
</code>```

Usage

```<code>dotnet updatealltools
</code>```

dotnet-campus/dotnetCampus.UpdateAllDotNetTools: The dotnet tool that can update all dotnet tools

Body:
I write a tool that can update all dotnet tool

Installation

dotnet tool install --global dotnetCampus.UpdateAllDotNetTools

Usage

dotnet updatealltools

dotnet-campus/dotnetCampus.UpdateAllDotNetTools: The dotnet tool that can update all dotnet tools


问:
Select all but the data based on search
I have a little problem with select all, I copied the code from https://stackblitz.com/edit/angular-t2ay62?file=src/template-header-footer-example.component.html
. but I want to make select all based on the value in search.

for example, I have data 5 [A, BA, C, D, E] and I search for only the letter A, then the data will appear [A, BA] and when I click select all, only data [A, BA] will be selected , not all data.

答:
There is an output event in ng-select called search. You can use that to filter data

You can do following changes in your ts and html
I have added one more property to class named activePeople which will store filtered data.

TS

```<code>import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
    selector: 'template-header-footer-example',
    templateUrl: './template-header-footer-example.component.html',
    styleUrls: ['./template-header-footer-example.component.scss']
})
export class TemplateHeaderFooterExampleComponent implements OnInit {

people = [];
selectedPeople = [];

activePeople = [];

constructor(private dataService: DataService) {
}

ngOnInit() {
    this.dataService.getPeople().subscribe(items => {
        this.people = items;
        this.activePeople = items;
    });
}

selectAll() {
    this.selectedPeople = this.activePeople.map(x => x.name);
}

unselectAll() {
    this.selectedPeople = [];
}

onSearch(event) {
  this.activePeople = event.items;
}

}
</code>```

HTML

```<code><ng-select
[multiple]="true"
[items]="people"
[(ngModel)]="selectedPeople"
placeholder="Select people"
bindLabel="name"
bindValue="name"
(search)="onSearch($event)">
</code>```

You can find more such events on
https://github.com/ng-select/ng-select/blob/master/src/demo/app/examples/output-events-example/output-events-example.component.html

Title: Select all but the data based on search

Body:
There is an output event in ng-select called search. You can use that to filter data

You can do following changes in your ts and html
I have added one more property to class named activePeople which will store filtered data.

TS

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
    selector: 'template-header-footer-example',
    templateUrl: './template-header-footer-example.component.html',
    styleUrls: ['./template-header-footer-example.component.scss']
})
export class TemplateHeaderFooterExampleComponent implements OnInit {

people = [];
selectedPeople = [];

activePeople = [];

constructor(private dataService: DataService) {
}

ngOnInit() {
    this.dataService.getPeople().subscribe(items => {
        this.people = items;
        this.activePeople = items;
    });
}

selectAll() {
    this.selectedPeople = this.activePeople.map(x => x.name);
}

unselectAll() {
    this.selectedPeople = [];
}

onSearch(event) {
  this.activePeople = event.items;
}

}

HTML

<ng-select
[multiple]="true"
[items]="people"
[(ngModel)]="selectedPeople"
placeholder="Select people"
bindLabel="name"
bindValue="name"
(search)="onSearch($event)">

You can find more such events on
https://github.com/ng-select/ng-select/blob/master/src/demo/app/examples/output-events-example/output-events-example.component.html


答:
So you are trying to fit a polynomial curve to your points. Let's break down how curve fitting for 2d points works. For simplicity, I've picked up 2nd order polynomial to fit the points. Also, I took the liberty of renaming your point names (a -> x and b ->y).

np.polyfit returns polynomial coefficients against your specified order. You can make an actual polynomial class via applying np.poly1d to the returned coefficients. To plot the polynomial, we fit the x and get z. This (x,z) points are our fitted curve.

import numpy as np
from matplotlib import pyplot as plt

x = [
    0.5365140382771445,
    0.5214107372135204,
    0.49844631119258076,
    0.4681910992517213,
    0.4310817214420628,
    0.3882500155177606,
    0.340292343154754,
    0.2880252732908801,
]
y = [
    0.7416012836460293,
    0.697385422521102,
    0.6561831711375956,
    0.6187959941327967,
    0.585900754784896,
    0.5586375446776617,
    0.537388969490203,
    0.5229339200070606,
]

# fitting x, y in a second order equation
# this returns the coefficient of p_0*x^2 + p_1*x + p_n = 0
# building the polynomial
poly = np.poly1d(np.polyfit(x, y, 2))

# getting the points for plotting polynomial
z = poly(x)

plt.figure(figsize=(8, 8))

# scatter plotting the actual value
plt.scatter(x, y, c="blue", marker="o", label="original points")

# plotting the polynomial curve
plt.plot(x, z, c="red", label="fitted curve (2nd order)")
plt.legend()
plt.show()
```

This returns,

Title: How to smooth a line in python3?

Body:
How to smooth this blue line, please?

import numpy as np
from matplotlib import pyplot as plt

a = [0.5365140382771445, 0.5214107372135204, 0.49844631119258076, 0.4681910992517213, 0.4310817214420628, 0.3882500155177606, 0.340292343154754, 0.2880252732908801]
b = [0.7416012836460293, 0.697385422521102, 0.6561831711375956, 0.6187959941327967, 0.585900754784896, 0.5586375446776617, 0.537388969490203, 0.5229339200070606]

time_fit = np.arange(len(b))
fitx = np.polyfit(time_fit, a, 2)
fity = np.polyfit(time_fit, b, 2)
x_fit = np.poly1d(fitx)
y_fit = np.poly1d(fity)

plt.figure(figsize=(8, 8))
plt.plot(x_fit, y_fit, c='red')
plt.plot(a, b, c = 'blue')
plt.show()

Do I fit it with the wrong polynomial?

Body:
So you are trying to fit a polynomial curve to your points. Let's break down how curve fitting for 2d points works. For simplicity, I've picked up 2nd order polynomial to fit the points. Also, I took the liberty of renaming your point names (a -> x and b ->y).

np.polyfit returns polynomial coefficients against your specified order. You can make an actual polynomial class via applying np.poly1d to the returned coefficients. To plot the polynomial, we fit the x and get z. This (x,z) points are our fitted curve.

import numpy as np
from matplotlib import pyplot as plt

x = [
    0.5365140382771445,
    0.5214107372135204,
    0.49844631119258076,
    0.4681910992517213,
    0.4310817214420628,
    0.3882500155177606,
    0.340292343154754,
    0.2880252732908801,
]
y = [
    0.7416012836460293,
    0.697385422521102,
    0.6561831711375956,
    0.6187959941327967,
    0.585900754784896,
    0.5586375446776617,
    0.537388969490203,
    0.5229339200070606,
]

# fitting x, y in a second order equation
# this returns the coefficient of p_0*x^2 + p_1*x + p_n = 0
# building the polynomial
poly = np.poly1d(np.polyfit(x, y, 2))

# getting the points for plotting polynomial
z = poly(x)

plt.figure(figsize=(8, 8))

# scatter plotting the actual value
plt.scatter(x, y, c="blue", marker="o", label="original points")

# plotting the polynomial curve
plt.plot(x, z, c="red", label="fitted curve (2nd order)")
plt.legend()
plt.show()

This returns,


问:
After clicking button component should render EditChannel Component should render
After clicking Button EditChannel component should render. Right now if  I before clicking on button EditChannel re-rendering as many as times as list item. After clicking also happening the same. I only want after clicking on button. Please find below lines for code. After clicking EditChannel component should render
Channel card component</p>

```<code>import React, { Fragment } from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Typography, Button } from "@material-ui/core";
import Avatar from "@material-ui/core/Avatar";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { channelFollow, channelFetchById } from "../../../redux/action/channel";
import EditChannel from "../../Channels/List/Edit";

const ChannelCard = props => {
  const classes = useStyles();
  const { channel, channelFetchById } = props;
  const [open, setOpen] = React.useState(false);
  const handleClickOpen = () => {
    setOpen(true);
  };
  const view = (
    <div className={classes.card}>
      <Link to={`/channels/${channel._id}`} className={classes.link}>
        <div className={classes.root}>
          <Avatar
            alt="Remy Sharp"
            src={channel.avatar}
            className={classes.bigAvatar}
          />
        </div>

        <div className={classes.title}>
          <Typography
            variant="subtitle1"
            align="center"
            className={classes.text}
          >
            {channel.channelName}
          </Typography>
          <Typography variant="body2" align="center">
            {channel.introduction}
          </Typography>
        </div>
      </Link>
      <Typography variant="body2" align="center" className={classes.text1}>
        {channel.follows ? channel.follows.length : 0} followers <br />
        Language:{channel.language}
      </Typography>
      <div className={classes.center}>
        <div className={classes.button}>
          <div className={classes.buttons}>
            <Button
              variant="contained"
              color="primary"
              onClick={() => {
                channelFetchById(channel._id);
                handleClickOpen();
              }}
            >
              Edit
            </Button>
            {handleClickOpen ? (
              <EditChannel setOpen={setOpen} open={open} />
            ) : null}
          </div>
          <div>
            <Button color="primary" variant="contained">
              Delete
            </Button>
          </div>
        </div>

        <br />
      </div>
    </div>
  );
  return <Fragment>{view}</Fragment>;
};
export default connect(null, { channelFollow, channelFetchById })(ChannelCard);
</code>```

答:
I guess instead of handleClickOpen only open will work like this,

```<code>   {open ? (
     <EditChannel setOpen={setOpen} open={open} />
   ) : null}
</code>```

Because handleClickOpen is click event not boolean variable

Body:
After clicking Button EditChannel component should render. Right now if  I before clicking on button EditChannel re-rendering as many as times as list item. After clicking also happening the same. I only want after clicking on button. Please find below lines for code. After clicking EditChannel component should render
Channel card component

import React, { Fragment } from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Typography, Button } from "@material-ui/core";
import Avatar from "@material-ui/core/Avatar";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { channelFollow, channelFetchById } from "../../../redux/action/channel";
import EditChannel from "../../Channels/List/Edit";

const ChannelCard = props => {
  const classes = useStyles();
  const { channel, channelFetchById } = props;
  const [open, setOpen] = React.useState(false);
  const handleClickOpen = () => {
    setOpen(true);
  };
  const view = (

      <Link to={`/channels/${channel._id}`} className={classes.link}>

          <Avatar
            alt="Remy Sharp"
            src={channel.avatar}
            className={classes.bigAvatar}
          />

          <Typography
            variant="subtitle1"
            align="center"
            className={classes.text}
          >
            {channel.channelName}
          </Typography>
          <Typography variant="body2" align="center">
            {channel.introduction}
          </Typography>

      </Link>
      <Typography variant="body2" align="center" className={classes.text1}>
        {channel.follows ? channel.follows.length : 0} followers

        Language:{channel.language}
      </Typography>

            <Button
              variant="contained"
              color="primary"
              onClick={() => {
                channelFetchById(channel._id);
                handleClickOpen();
              }}
            >
              Edit
            </Button>
            {handleClickOpen ? (
              <EditChannel setOpen={setOpen} open={open} />
            ) : null}

            <Button color="primary" variant="contained">
              Delete
            </Button>

  );
  return <Fragment>{view}</Fragment>;
};
export default connect(null, { channelFollow, channelFetchById })(ChannelCard);

Body:
I guess instead of handleClickOpen only open will work like this,

   {open ? (
     <EditChannel setOpen={setOpen} open={open} />
   ) : null}

Because handleClickOpen is click event not boolean variable


问:
How to fix this 'Google Maps JavaScript API error: InvalidKeyMapError' error in angular 6?
I am using google map in my Angular 6 app.

I have been using this Google map in another project too. but recently I start another project and install angular agm. then used the API key that i used previous project. but it did not work. Said 'that it is an invalid key'. so i got new API key , but there is same problem.
this is the problem that shows in browser.

```<code>Google Maps JavaScript API warning: InvalidKey https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key util.js:222:33
Google Maps JavaScript API error: InvalidKeyMapError
https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error js:51:110
_.Jc
https://maps.googleapis.com/maps/api/js:51:110
on/this.l</<
https://maps.googleapis.com/maps-api-v3/api/js/35/8/common.js:73:375
_.qn</<
https://maps.googleapis.com/maps-api-v3/api/js/35/8/common.js:138:172
c
https://maps.googleapis.com/maps-api-v3/api/js/35/8/common.js:67:82
<anonymous>
https://maps.googleapis.com/maps/api/js/AuthenticationService.Authenticate:1:22

</code>```

map.component.html

```<code><agm-map [latitude]="mapDetails.latitude" [longitude]="mapDetails.longitude" (mapClick)=" onChooseLocation($event)">
  <agm-marker [latitude]="mapDetails.latitude" [longitude]="mapDetails.longitude"></agm-marker>
</agm-map>
</code>```

map.component.ts

```<code>import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { MapDetails } from '../shared/models/map-details.model';

@Component({
  selector: 'app-maps',
  templateUrl: './maps.component.html',
  styleUrls: ['./maps.component.css']
})
export class MapsComponent implements OnInit {
  mapDetails: MapDetails = new MapDetails();

  @Output() public mapClickEvent = new EventEmitter();
  constructor() { }

  ngOnInit() {
    this.mapDetails.latitude=6.9271;
    this.mapDetails.longitude=79.8612;
  }
  onChooseLocation(event){
      this.mapDetails.latitude=event.coords.lat;
      this.mapDetails.longitude=event.coords.lng;
      this.mapClickEvent.emit(this.mapDetails);

  }
}
</code>```

user-layout.module.ts

```<code>import { JobDoneComponent } from './../../job-done/job-done.component';
import { RatingComponent } from './../../rating/rating.component';
import { NotificationsComponent } from './../../notifications/notifications.component';
import { ProvidedJobsComponent } from './../../provided-jobs/provided-jobs.component';
import { CompletedJobsComponent } from './../../completed-jobs/completed-jobs.component';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { UserLayoutRoutes } from './user-layout.routing';

import { UserProfileComponent } from '../../user-profile/user-profile.component';

import { ChartsModule } from 'ng2-charts';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import {ComplainComponent} from '../../complain/complain.component';
import { UserLogInComponent } from 'app/user-log-in/user-log-in.component';
//import {MatButtonModule, MatCheckboxModule, MatDialog, MAT_DIALOG_DATA, MatDialogConfig} from '@angular/material';
import { MatFormFieldModule,MatCardModule,MatStepperModule,MatSelectModule,MatButtonModule, MatCheckboxModule, MatInputModule,MatDatepickerModule, MatNativeDateModule, MatToolbarModule, MatSidenavModule, MatIconModule, MatListModule} from '@angular/material';
import {MatDialogModule} from '@angular/material/dialog';

import { PostJobsComponent } from '../../post-jobs/post-jobs.component';
import { PostPaymentsComponent } from '../../post-payments/post-payments.component';
import {MapsComponent} from '../../maps/maps.component';
import { DraftPostComponent } from '../../draft-post/draft-post.component';
import { JobRequestComponent } from '../../job-request/job-request.component';
import { AgmCoreModule } from '@agm/core';

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(UserLayoutRoutes),
    FormsModule,
    ChartsModule,
    NgbModule,
    ToastrModule.forRoot(),
    AgmCoreModule.forRoot({
      apiKey:'My_API_KEY'
    }),
    MatDialogModule,
    MatFormFieldModule,
    MatCardModule,
    MatStepperModule,
    MatSelectModule,
    MatButtonModule,
    MatCheckboxModule,
    MatInputModule,
    MatNativeDateModule,
    MatToolbarModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule
  ],
  declarations: [
    PostJobsComponent,
    PostPaymentsComponent,
    DraftPostComponent,
    UserProfileComponent,
    JobRequestComponent,
    ComplainComponent,
    MapsComponent,
    CompletedJobsComponent,
    ProvidedJobsComponent,
    NotificationsComponent,
    JobDoneComponent,
    RatingComponent
  ],
  entryComponents: [RatingComponent]
})
export class UserLayoutModule { }
</code>```

答:
Although this might not be the best approach in those environments where the key is already being used at multiple places. It worked for me as I was using it at just 2 of the places in my project.

Deleting the existing key and regenerating a new key worked for me.

Body:
I am using google map in my Angular 6 app.

I have been using this Google map in another project too. but recently I start another project and install angular agm. then used the API key that i used previous project. but it did not work. Said 'that it is an invalid key'. so i got new API key , but there is same problem.
this is the problem that shows in browser.

Google Maps JavaScript API warning: InvalidKey https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key util.js:222:33
Google Maps JavaScript API error: InvalidKeyMapError
https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error js:51:110
_.Jc
https://maps.googleapis.com/maps/api/js:51:110
on/this.l</<
https://maps.googleapis.com/maps-api-v3/api/js/35/8/common.js:73:375
_.qn</<
https://maps.googleapis.com/maps-api-v3/api/js/35/8/common.js:138:172
c
https://maps.googleapis.com/maps-api-v3/api/js/35/8/common.js:67:82
<anonymous>
https://maps.googleapis.com/maps/api/js/AuthenticationService.Authenticate:1:22

map.component.html

<agm-map [latitude]="mapDetails.latitude" [longitude]="mapDetails.longitude" (mapClick)=" onChooseLocation($event)">
  <agm-marker [latitude]="mapDetails.latitude" [longitude]="mapDetails.longitude"></agm-marker>
</agm-map>

map.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { MapDetails } from '../shared/models/map-details.model';

@Component({
  selector: 'app-maps',
  templateUrl: './maps.component.html',
  styleUrls: ['./maps.component.css']
})
export class MapsComponent implements OnInit {
  mapDetails: MapDetails = new MapDetails();

  @Output() public mapClickEvent = new EventEmitter();
  constructor() { }

  ngOnInit() {
    this.mapDetails.latitude=6.9271;
    this.mapDetails.longitude=79.8612;
  }
  onChooseLocation(event){
      this.mapDetails.latitude=event.coords.lat;
      this.mapDetails.longitude=event.coords.lng;
      this.mapClickEvent.emit(this.mapDetails);

  }
}

user-layout.module.ts

import { JobDoneComponent } from './../../job-done/job-done.component';
import { RatingComponent } from './../../rating/rating.component';
import { NotificationsComponent } from './../../notifications/notifications.component';
import { ProvidedJobsComponent } from './../../provided-jobs/provided-jobs.component';
import { CompletedJobsComponent } from './../../completed-jobs/completed-jobs.component';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { UserLayoutRoutes } from './user-layout.routing';

import { UserProfileComponent } from '../../user-profile/user-profile.component';

import { ChartsModule } from 'ng2-charts';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import {ComplainComponent} from '../../complain/complain.component';
import { UserLogInComponent } from 'app/user-log-in/user-log-in.component';
//import {MatButtonModule, MatCheckboxModule, MatDialog, MAT_DIALOG_DATA, MatDialogConfig} from '@angular/material';
import { MatFormFieldModule,MatCardModule,MatStepperModule,MatSelectModule,MatButtonModule, MatCheckboxModule, MatInputModule,MatDatepickerModule, MatNativeDateModule, MatToolbarModule, MatSidenavModule, MatIconModule, MatListModule} from '@angular/material';
import {MatDialogModule} from '@angular/material/dialog';

import { PostJobsComponent } from '../../post-jobs/post-jobs.component';
import { PostPaymentsComponent } from '../../post-payments/post-payments.component';
import {MapsComponent} from '../../maps/maps.component';
import { DraftPostComponent } from '../../draft-post/draft-post.component';
import { JobRequestComponent } from '../../job-request/job-request.component';
import { AgmCoreModule } from '@agm/core';

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(UserLayoutRoutes),
    FormsModule,
    ChartsModule,
    NgbModule,
    ToastrModule.forRoot(),
    AgmCoreModule.forRoot({
      apiKey:'My_API_KEY'
    }),
    MatDialogModule,
    MatFormFieldModule,
    MatCardModule,
    MatStepperModule,
    MatSelectModule,
    MatButtonModule,
    MatCheckboxModule,
    MatInputModule,
    MatNativeDateModule,
    MatToolbarModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule
  ],
  declarations: [
    PostJobsComponent,
    PostPaymentsComponent,
    DraftPostComponent,
    UserProfileComponent,
    JobRequestComponent,
    ComplainComponent,
    MapsComponent,
    CompletedJobsComponent,
    ProvidedJobsComponent,
    NotificationsComponent,
    JobDoneComponent,
    RatingComponent
  ],
  entryComponents: [RatingComponent]
})
export class UserLayoutModule { }


问:
C# Winforms and MySQL: Use "Number" or "Code" properties from MySqlException exception for show custom message in the form
[EDIT]: When you have a MySqlException, you catch it; so the question is which property is for the MySQL error code, like:

No connection to host (1042 err code)

Timeout query

Table no exists

Duplicated Unique key, etc

So, which property from MySqlException get the error code: "Number" or "Code". With the value, I show custom message like icon change color and/or text in status bar

THANKS to Bradley Grainger for answering and for have described the difference between both properties, Thank you very much.

答:
You will want to use MySqlException.Number in your code when checking the error code.

MySqlException.Number is the "original" error code property. It is an integer that can be cast to a MySqlErrorCode enumeration value to interpret the number.

MySqlException.Code is a new property added in MySql.Data 8.0. It is for the new "X Protocol" and isn't used by regular connections to a MySQL database.

This isn't documented anywhere that I've found, but it can be seen in the code that Number is set for the standard protocol, and Code is set for the X Protocol.

If you use MySqlConnector, there's a strongly-typed MySqlException.ErrorCode property that returns the error code as a MySqlErrorCode enum value, not an int.


问:
Pointer as parameter in Linux kernel code

    Recently, I have read the linux kernel code to see how the code looks like. I understands only the basic of pointers.

So, i came across this function declaration:-

```<code>kernel_write(struct file *file, const void *buf, size_t count,loff_t *pos)
</code>```

What does struct file *file imply?

Based on my understanding, struct file *file means that you pass the pointer that points to the memory blocks that contains multiple file structs?

Here is a diagram to visualize my understanding :-

Is my understanding accurate or i am actually misguided?

答:
There are multiple reasons to use a pointer as a parameter.

The pointer points to an array of items.  You need to know how many items so there must be a count or size parameter to indicate how big the array is.  The buf parameter is an array and the count parameter indicates how big it is.

The pointer is used to avoid copying a huge structure via the stack.  Functions receive a copy of the item passed to them.  If the structure is really big then copying the entire structure is a bad idea but passing a pointer is a much smaller thing so it is a better idea.

The pointer is used to allow the function to modify the value passed to it.  Functions receive a copy of the item passed to them.  So modifying the parameter only modifies the copy and not the original.  If a pointer is passed then you can't modify where the pointer points but you can modify what the pointer points at.

In the particular example you show I can't tell if they pass a pointer to file because they need to modify the contents of the structure (#3) or because the structure is really big and they are worried about how much stack space the copy will take up (#2).  But it is almost certainly NOT an array (#1) because there is no size or count parameter to say how big the array is (which means the pointer can only point at one structure).

If you want some examples of each case let me know.

Body:
Recently, I have read the linux kernel code to see how the code looks like. I understands only the basic of pointers.

So, i came across this function declaration:-

kernel_write(struct file *file, const void *buf, size_t count,loff_t *pos)

What does struct file *file imply?

Based on my understanding, struct file *file means that you pass the pointer that points to the memory blocks that contains multiple file structs?

Here is a diagram to visualize my understanding :-

Is my understanding accurate or i am actually misguided?


问:
How to create angular 9 project?
I tried to install angular cli 9

```<code>npm i -g @angular/cli@9.0.0-rc.0
</code>```

and run

```<code> ng new some-project
</code>```

I get this error:

```<code> PS C:> ng new ng9
internal/modules/cjs/loader.js:797
    throw err;
    ^

Error: Cannot find module '@angular-devkit/core'
Require stack:
- C:\Users\\AppData\Roaming\npm\node_modules\@angular\cli\lib\init.js
- C:\Users\\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
</code>```

答:
You can easily create an Angular 9 project using the latest version of Angular CLI.

You first need to make sure you have a recent version of node and npm installed on your development machine.

Next, install the latest version of Angular CLI using the following command:

npm install @angular/cli
```

<p>Next, run the <code>ng new</code> command to create a new project:</p>

<pre class="lang-sh prettyprint-override"><code>ng new my-project
</code>```

Title: How to create angular 9 project?

Body:
I tried to install angular cli 9

npm i -g @angular/cli@9.0.0-rc.0

and run

 ng new some-project

I get this error:

 PS C:> ng new ng9
internal/modules/cjs/loader.js:797
    throw err;
    ^

Error: Cannot find module '@angular-devkit/core'
Require stack:
- C:\Users\\AppData\Roaming\npm\node_modules\@angular\cli\lib\init.js
- C:\Users\\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng

Body:
You can easily create an Angular 9 project using the latest version of Angular CLI.

You first need to make sure you have a recent version of node and npm installed on your development machine.

Next, install the latest version of Angular CLI using the following command:

npm install @angular/cli

Next, run the ng new command to create a new project:

ng new my-project


问:
can't pip install mysql-python
I'm trying to get django/pip/mysql working and i can't seem to figure out how to install mysql-python. this is the error i receive when trying to install mysql-python

```
pip install mysql-python

Downloading/unpacking mysql-python
  Downloading MySQL-python-1.2.4.zip (113kB): 113kB downloaded
  Running setup.py egg_info for package mysql-python
    Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz
    Extracting in /tmp/tmp5jjdpf
    Now working in /tmp/tmp5jjdpf/distribute-0.6.28
    Building a Distribute egg in /home/brian/flaskapp/build/mysql-python
    /home/brian/flaskapp/build/mysql-python/distribute-0.6.28-py2.7.egg

Installing collected packages: mysql-python
  Running setup.py install for mysql-python
    building '_mysql' extension
    x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG
    _mysql.c:29:20: fatal error: Python.h: No such file or directory
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
    Complete output from command /home/brian/flaskapp/bin/python -c "import setuptools;__file__='/home/brian/flaskapp/build/mysql-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-Ur7r16-record/install-record.txt --single-version-externally-managed --install-headers /home/brian/flaskapp/include/site/python2.7:
    running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb

creating build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

running build_ext

building '_mysql' extension

creating build/temp.linux-x86_64-2.7

x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG

_mysql.c:29:20: fatal error: Python.h: No such file or directory

compilation terminated.

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /home/brian/flaskapp/bin/python -c "import setuptools;__file__='/home/brian/flaskapp/build/mysql-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-Ur7r16-record/install-record.txt --single-version-externally-managed --install-headers /home/brian/flaskapp/include/site/python2.7 failed with error code 1 in /home/brian/flaskapp/build/mysql-python
Storing complete log in /home/brian/.pip/pip.log
```

Googling reveals i need to install python-dev but whenever i try to install with

```<code>sudo apt-get install python-dev
</code>```

i get this error:

```E: Package 'python-dev' has no installation candidate```

I'm currently using linux mint 15 RC and i think that might be the issue...but i'm not sure.
I'm out of ideas:(

答:
First create path as below by running into terminal

export PATH=/usr/local/mysql/bin:$PATH

After doing this run following command to terminal

sudo pip3 install flask-mysqldb

Title: can't pip install mysql-python

Body:
I'm trying to get django/pip/mysql working and i can't seem to figure out how to install mysql-python. this is the error i receive when trying to install mysql-python

pip install mysql-python

Downloading/unpacking mysql-python
  Downloading MySQL-python-1.2.4.zip (113kB): 113kB downloaded
  Running setup.py egg_info for package mysql-python
    Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz
    Extracting in /tmp/tmp5jjdpf
    Now working in /tmp/tmp5jjdpf/distribute-0.6.28
    Building a Distribute egg in /home/brian/flaskapp/build/mysql-python
    /home/brian/flaskapp/build/mysql-python/distribute-0.6.28-py2.7.egg

Installing collected packages: mysql-python
  Running setup.py install for mysql-python
    building '_mysql' extension
    x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG
    _mysql.c:29:20: fatal error: Python.h: No such file or directory
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
    Complete output from command /home/brian/flaskapp/bin/python -c "import setuptools;__file__='/home/brian/flaskapp/build/mysql-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-Ur7r16-record/install-record.txt --single-version-externally-managed --install-headers /home/brian/flaskapp/include/site/python2.7:
    running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb

copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb

creating build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants

running build_ext

building '_mysql' extension

creating build/temp.linux-x86_64-2.7

x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG

_mysql.c:29:20: fatal error: Python.h: No such file or directory

compilation terminated.

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /home/brian/flaskapp/bin/python -c "import setuptools;__file__='/home/brian/flaskapp/build/mysql-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-Ur7r16-record/install-record.txt --single-version-externally-managed --install-headers /home/brian/flaskapp/include/site/python2.7 failed with error code 1 in /home/brian/flaskapp/build/mysql-python
Storing complete log in /home/brian/.pip/pip.log

Googling reveals i need to install python-dev but whenever i try to install with

sudo apt-get install python-dev

i get this error:

E: Package 'python-dev' has no installation candidate

I'm currently using linux mint 15 RC and i think that might be the issue...but i'm not sure.
I'm out of ideas:(


答:
I think the Flexible causes the chart to fill the parent's height, which is infinite. Try wrapping it in a Column instead to give a pre-calculated size.

```<code>body: ListView(
    children: <Widget>[
      Row(
        children: <Widget>[
          FlatButton(onPressed: (){
            print("flat button pressed");
          }, child: Text("Flat Button 1")),
          FlatButton(onPressed: (){
            print("flat button pressed");
          }, child: Text("Flat Button 2")),
          FlatButton(onPressed: (){
            print("flat button pressed");
          }, child: Text("Flat Button 3")),
        ],
        mainAxisAlignment: MainAxisAlignment.center,
      ),
      Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [GroupedStackedBarChart.withRandomData()],
      ),
    ],
  ),
</code>```

Title: How to make Widget not overflow ListView on Flutter Web

Body:
Context: I'm trying to make a web app with Flutter - so this is all in Chrome

Problem: I have a chart, from the charts_flutter library, and it renders OK when inside a Column. The issue is that I want to be able to scroll and add more content below the chart. When I try changing the column to a ListView, it overflows (seems the Chart is trying to be as big as possible and the ListView has infinite height). I'm not sure how to get around this issue.

Current Code:
Just the scaffold, because that's all that I think is important here

Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: ListView(
        children: <Widget>[
          Row(
            children: <Widget>[
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 1")),
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 2")),
              FlatButton(onPressed: (){
                print("flat button pressed");
              }, child: Text("Flat Button 3")),
            ],
            mainAxisAlignment: MainAxisAlignment.center,
          ),
          Flexible(child: GroupedStackedBarChart.withRandomData()),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );

Body:
I think the Flexible causes the chart to fill the parent's height, which is infinite. Try wrapping it in a Column instead to give a pre-calculated size.

body: ListView(
    children: <Widget>[
      Row(
        children: <Widget>[
          FlatButton(onPressed: (){
            print("flat button pressed");
          }, child: Text("Flat Button 1")),
          FlatButton(onPressed: (){
            print("flat button pressed");
          }, child: Text("Flat Button 2")),
          FlatButton(onPressed: (){
            print("flat button pressed");
          }, child: Text("Flat Button 3")),
        ],
        mainAxisAlignment: MainAxisAlignment.center,
      ),
      Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [GroupedStackedBarChart.withRandomData()],
      ),
    ],
  ),


问:
Why does including tau.js in Tizen app break everything else?
I'm working on an app for the Samsung Galaxy watch (Tizen version 4.0) using Tizen studio and I've run into a frustrating issue. To give you some background, Samsung places a lot of emphasis on using their Tizen Advanced UI framework in mobile and wearable apps. This framework supposedly makes it easy to add standard UI components to your projects.

The issue I'm running into is that as soon as I add the tau.js script to my project, nearly everything else stops working. This is pretty annoying because the TAU library does offer some helpful things like the circle-helper which makes scrolling lists on the Samsung watch super easy with the Bezel.

In my project, I added a click listener to one of the spans on this page ("Current").

Without the tau.js script added, clicking on the span does exactly what I want. As soon as I add the script however (I've tried adding it in the head and body section, above and below my own script), no clicks are ever registered. It's as if the tau.js script is blocking my own script.

Another interesting thing is that when I add the tau.js file, my accelerometer values are no longer produced and everything reads zero. If I add the accelerometer-reading script to the bottom of the tau.js file it will work but the click functionality still doesn't work.

Finally, I have been able to add a click listener to the document as a whole like this:

```<code>document.addEventListener("click",myFunction);
</code>```

That works fine but it's driving me crazy that I can't add event listeners to any other HTML elements.

I'm fairly new to HTML/CSS/Javascript so maybe I'm missing something fundamental. What would cause one script to override another script? Why does adding the tau.js file seem to ruin everything? You can find the tau.js code here. Thanks!

答:
I was able to resolve my problem by moving all of my code to one html file and using TAU page management. It looked like this listener...

```<code>document.addEventListener('DOMContentLoaded',function()
</code>```

wasn't being triggered when I navigated to the new page. Adding all of the javascript files to one page fixed my issue.

Body:
I'm working on an app for the Samsung Galaxy watch (Tizen version 4.0) using Tizen studio and I've run into a frustrating issue. To give you some background, Samsung places a lot of emphasis on using their Tizen Advanced UI framework in mobile and wearable apps. This framework supposedly makes it easy to add standard UI components to your projects.

The issue I'm running into is that as soon as I add the tau.js script to my project, nearly everything else stops working. This is pretty annoying because the TAU library does offer some helpful things like the circle-helper which makes scrolling lists on the Samsung watch super easy with the Bezel.

In my project, I added a click listener to one of the spans on this page ("Current").

Without the tau.js script added, clicking on the span does exactly what I want. As soon as I add the script however (I've tried adding it in the head and body section, above and below my own script), no clicks are ever registered. It's as if the tau.js script is blocking my own script.

Another interesting thing is that when I add the tau.js file, my accelerometer values are no longer produced and everything reads zero. If I add the accelerometer-reading script to the bottom of the tau.js file it will work but the click functionality still doesn't work.

Finally, I have been able to add a click listener to the document as a whole like this:

document.addEventListener("click",myFunction);

That works fine but it's driving me crazy that I can't add event listeners to any other HTML elements.

I'm fairly new to HTML/CSS/Javascript so maybe I'm missing something fundamental. What would cause one script to override another script? Why does adding the tau.js file seem to ruin everything? You can find the tau.js code here. Thanks!

Body:
I was able to resolve my problem by moving all of my code to one html file and using TAU page management. It looked like this listener...

document.addEventListener('DOMContentLoaded',function()

wasn't being triggered when I navigated to the new page. Adding all of the javascript files to one page fixed my issue.


问:
Updating CSS variables with attr()
Why is it that this works, and yields the :before and it says "changed"

:root {
    --namevar: "fallback";
}

.in[name] {
    --namevar: "changed";
}

.in dd:first-of-type:before {
    font-weight: bold;
    display: block;
    content: var(--namevar);
}
```

<p>But if you change it to this, the <code>:before</code> is lost?</p>

<pre class="lang-css prettyprint-override"><code>.in[name] {
    --namevar: attr(name);
}
</code>```

Nor do either of these work:

.in dd:first-of-type:before {
    content: attr(name, inherit);
}
```

<pre class="lang-css prettyprint-override"><code>.in[name] dd {
    name: inherit;
}
</code>```

The HTML would look something like:

one

two

three

```

What am I missing here?

答:
This is because your css variable detect nearest parents variable.
you can override using global selector "*"

just use in css

```<code>*{
    --namevar: "fallback";
}

</code>```

and try it. if any more help. feel free to ask me.

Title: Updating CSS variables with attr()

Body:
Why is it that this works, and yields the :before and it says "changed"

:root {
    --namevar: "fallback";
}

.in[name] {
    --namevar: "changed";
}

.in dd:first-of-type:before {
    font-weight: bold;
    display: block;
    content: var(--namevar);
}

But if you change it to this, the :before is lost?

.in[name] {
    --namevar: attr(name);
}

Nor do either of these work:

.in dd:first-of-type:before {
    content: attr(name, inherit);
}

.in[name] dd {
    name: inherit;
}

The HTML would look something like:

one

two

three

What am I missing here?

Body:
This is because your css variable detect nearest parents variable.
you can override using global selector "*"

just use in css

*{
    --namevar: "fallback";
}

and try it. if any more help. feel free to ask me.