问:
MySQL slow query with SELECT/ORDER BY on one table with WHERE on another, LIMIT results
I'm trying to query the top N rows from a couple of tables.  The WHERE clause refers to a list of columns in one table, whereas the ORDER BY clause refers to columns in the other.  It looks like MySQL is choosing the table involved in my WHERE clause for its first pass of filtering (which doesn't filter much) whereas it's the ORDER BY that affects the rows returned once I apply the LIMIT.  If I force MySQL to use a covering index for the ORDER BY, the query returns immediately with the desired rows.  Unfortunately I can't pass index hints to MySQL through JPA, and rewriting everything using native queries would be a substantial amount of work.  Here's an illustrative example:

```<code>CREATE TABLE person (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(255),
    last_name VARCHAR(255)
) engine=InnoDB;

CREATE TABLE membership (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL
) engine=InnoDB;

CREATE TABLE employee (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    membership_id INTEGER NOT NULL,
    type VARCHAR(15),
    enabled BIT NOT NULL,
    person_id INTEGER NOT NULL REFERENCES person ( id ),
    CONSTRAINT fk_employee_membership_id FOREIGN KEY ( membership_id ) REFERENCES membership ( id ),
    CONSTRAINT fk_employee_person_id FOREIGN KEY ( person_id ) REFERENCES person ( id )
) engine=InnoDB;

CREATE UNIQUE INDEX uk_employee_person_id ON employee ( person_id );

CREATE INDEX idx_person_first_name_last_name ON person ( first_name, last_name );
</code>```

I wrote a script to output a bunch of INSERT statements to populate the tables with 200'000 rows:

#!/bin/bash
#
echo "INSERT INTO membership ( id, name ) VALUES ( 1, 'Default Membership' );"
for seq in {1..200000}; do
    echo "INSERT INTO person ( id, first_name, last_name ) VALUES ( $seq, 'firstName$seq', 'lastName$seq' );"
    echo "INSERT INTO employee ( id, membership_id, type, enabled, person_id ) VALUES ( $seq, 1, 'INDIVIDUAL', 1, $seq );"
done
```

<p>My first attempt:</p>

```SELECT e.*
FROM person p INNER JOIN employee e ON p.id = e.person_id
WHERE e.membership_id = 1 AND type = 'INDIVIDUAL' AND enabled = 1
ORDER BY p.first_name ASC, p.last_name ASC, p.id ASC
LIMIT 100;
-- 100 rows in set (1.43 sec)
```

<p>and the EXPLAIN:
</p>

```+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------+---------+--------------------+-------+----------+----------------------------------------------+
| id | select_type | table | partitions | type   | possible_keys                                   | key                       | key_len | ref                | rows  | filtered | Extra                                        |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------+---------+--------------------+-------+----------+----------------------------------------------+
|  1 | SIMPLE      | e     | NULL       | ref    | uk_employee_person_id,fk_employee_membership_id | fk_employee_membership_id | 4       | const              | 99814 |     5.00 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | p     | NULL       | eq_ref | PRIMARY                                         | PRIMARY                   | 4       | qsuite.e.person_id |     1 |   100.00 | NULL                                         |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------+---------+--------------------+-------+----------+----------------------------------------------+
```

<p>Now I force MySQL to use the ( first_name, last_name ) index on person:</p>

```SELECT e.*
FROM person p USE INDEX ( idx_person_first_name_last_name )
    INNER JOIN employee e ON p.id = e.person_id
WHERE e.membership_id = 1 AND type = 'INDIVIDUAL' AND enabled = 1
ORDER BY p.first_name ASC, p.last_name ASC, p.id ASC
LIMIT 100;
-- 100 rows in set (0.00 sec)
```

<p>It returns instantly.  And the explain:
</p>

```+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------------+---------+-------------+------+----------+-------------+
| id | select_type | table | partitions | type   | possible_keys                                   | key                             | key_len | ref         | rows | filtered | Extra       |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------------+---------+-------------+------+----------+-------------+
|  1 | SIMPLE      | p     | NULL       | index  | NULL                                            | idx_person_first_name_last_name | 2046    | NULL        |  100 |   100.00 | Using index |
|  1 | SIMPLE      | e     | NULL       | eq_ref | uk_employee_person_id,fk_employee_membership_id | uk_employee_person_id           | 4       | qsuite.p.id |    1 |     5.00 | Using where |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------------+---------+-------------+------+----------+-------------+
```

<p>Note the WHERE clause in the example doesn't end up actually filtering any rows.  This is largely representative of the data I have and the bulk of queries against this table.  Is there a way to coax MySQL into using that index or some not-quite-destructive way of restructuring this to improve the performance?</p>

<p>Thanks.</p>

<p>Edit: I dropped the original covering index and added one to each of the tables:</p>

```CREATE INDEX idx_person_id_first_name_last_name ON person ( id, first_name, last_name );
CREATE INDEX idx_employee_etc ON employee ( membership_id, type, enabled, person_id );
```

<p>It seems to speed it up a little, but MySQL still insists on running through the employee table first:</p>

```+----+-------------+-------+------------+--------+--------------------------------------------+------------------+---------+--------------------+-------+----------+----------------------------------------------+
| id | select_type | table | partitions | type   | possible_keys                              | key              | key_len | ref                | rows  | filtered | Extra                                        |
+----+-------------+-------+------------+--------+--------------------------------------------+------------------+---------+--------------------+-------+----------+----------------------------------------------+
|  1 | SIMPLE      | e     | NULL       | ref    | uk_employee_person_id,idx_employee_etc     | idx_employee_etc | 68      | const,const,const  | 97311 |   100.00 | Using index; Using temporary; Using filesort |
|  1 | SIMPLE      | p     | NULL       | eq_ref | PRIMARY,idx_person_id_first_name_last_name | PRIMARY          | 4       | qsuite.e.person_id |     1 |   100.00 | NULL                                         |
+----+-------------+-------+------------+--------+--------------------------------------------+------------------+---------+--------------------+-------+----------+----------------------------------------------+
```

答:
Storing first and last names redundantly in the employee table is an option - But with drawbacks. You will have to manage the redundancy. To guarantee the consistency, you can make those columns part of the foreign key. ON UPDATE CASCADE will take you some work. But you will still need to rewrite your INSERT statements or use triggers. With first_name and last_name being part of the employee table, you would be able to create an optimal index for your query. The table would look the following way:

```<code>CREATE TABLE employee (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    membership_id INTEGER NOT NULL,
    type VARCHAR(15),
    enabled BIT NOT NULL,
    person_id INTEGER NOT NULL REFERENCES person ( id ),
    CONSTRAINT fk_employee_membership_id FOREIGN KEY ( membership_id ) REFERENCES membership ( id ),
    CONSTRAINT fk_employee_person FOREIGN KEY ( person_id, first_name, last_name )
                                  REFERENCES person ( id, first_name, last_name ),
    INDEX (membership_id, type, enabled, first_name, last_name, person_id)
) engine=InnoDB;
</code>```

The query would change to:

```<code>SELECT e.*
FROM employee e
WHERE e.membership_id = 1 AND e.type = 'INDIVIDUAL' AND e.enabled = 1
ORDER BY e.first_name ASC, e.last_name ASC, e.person_id ASC
LIMIT 100;
</code>```

However - I would avoid such changes if possible. There might be other ways to use an index for ORDER BY. I would first try to move the WHERE conditions into a correlated EXISTS subquery:

```<code>SELECT e.*
FROM person p INNER JOIN employee e ON p.id = e.person_id
WHERE EXISTS (
  SELECT *
  FROM employee e1
  WHERE e1.person_id = p.id
    AND e1.membership_id = 1
    AND e1.type = 'INDIVIDUAL'
    AND e1.enabled = 1
)
ORDER BY p.first_name ASC, p.last_name ASC, p.id ASC
LIMIT 100;
</code>```

Now, to evaluate the subquery, the engine needs p.id, so it has to start reading the data from person table first (which you will see in the execution plan). And I guess it will be smart enough to read it from the index. Note that in InnoDB the primary key is always part of any secondary key. So the idx_person_first_name_last_name index is actually on (first_name, last_name, id).

Body:
I'm trying to query the top N rows from a couple of tables.  The WHERE clause refers to a list of columns in one table, whereas the ORDER BY clause refers to columns in the other.  It looks like MySQL is choosing the table involved in my WHERE clause for its first pass of filtering (which doesn't filter much) whereas it's the ORDER BY that affects the rows returned once I apply the LIMIT.  If I force MySQL to use a covering index for the ORDER BY, the query returns immediately with the desired rows.  Unfortunately I can't pass index hints to MySQL through JPA, and rewriting everything using native queries would be a substantial amount of work.  Here's an illustrative example:

CREATE TABLE person (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(255),
    last_name VARCHAR(255)
) engine=InnoDB;

CREATE TABLE membership (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL
) engine=InnoDB;

CREATE TABLE employee (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    membership_id INTEGER NOT NULL,
    type VARCHAR(15),
    enabled BIT NOT NULL,
    person_id INTEGER NOT NULL REFERENCES person ( id ),
    CONSTRAINT fk_employee_membership_id FOREIGN KEY ( membership_id ) REFERENCES membership ( id ),
    CONSTRAINT fk_employee_person_id FOREIGN KEY ( person_id ) REFERENCES person ( id )
) engine=InnoDB;

CREATE UNIQUE INDEX uk_employee_person_id ON employee ( person_id );

CREATE INDEX idx_person_first_name_last_name ON person ( first_name, last_name );

I wrote a script to output a bunch of INSERT statements to populate the tables with 200'000 rows:

#!/bin/bash
#
echo "INSERT INTO membership ( id, name ) VALUES ( 1, 'Default Membership' );"
for seq in {1..200000}; do
    echo "INSERT INTO person ( id, first_name, last_name ) VALUES ( $seq, 'firstName$seq', 'lastName$seq' );"
    echo "INSERT INTO employee ( id, membership_id, type, enabled, person_id ) VALUES ( $seq, 1, 'INDIVIDUAL', 1, $seq );"
done

My first attempt:

SELECT e.*
FROM person p INNER JOIN employee e ON p.id = e.person_id
WHERE e.membership_id = 1 AND type = 'INDIVIDUAL' AND enabled = 1
ORDER BY p.first_name ASC, p.last_name ASC, p.id ASC
LIMIT 100;
-- 100 rows in set (1.43 sec)

and the EXPLAIN:

+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------+---------+--------------------+-------+----------+----------------------------------------------+
| id | select_type | table | partitions | type   | possible_keys                                   | key                       | key_len | ref                | rows  | filtered | Extra                                        |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------+---------+--------------------+-------+----------+----------------------------------------------+
|  1 | SIMPLE      | e     | NULL       | ref    | uk_employee_person_id,fk_employee_membership_id | fk_employee_membership_id | 4       | const              | 99814 |     5.00 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | p     | NULL       | eq_ref | PRIMARY                                         | PRIMARY                   | 4       | qsuite.e.person_id |     1 |   100.00 | NULL                                         |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------+---------+--------------------+-------+----------+----------------------------------------------+

Now I force MySQL to use the ( first_name, last_name ) index on person:

SELECT e.*
FROM person p USE INDEX ( idx_person_first_name_last_name )
    INNER JOIN employee e ON p.id = e.person_id
WHERE e.membership_id = 1 AND type = 'INDIVIDUAL' AND enabled = 1
ORDER BY p.first_name ASC, p.last_name ASC, p.id ASC
LIMIT 100;
-- 100 rows in set (0.00 sec)

It returns instantly.  And the explain:

+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------------+---------+-------------+------+----------+-------------+
| id | select_type | table | partitions | type   | possible_keys                                   | key                             | key_len | ref         | rows | filtered | Extra       |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------------+---------+-------------+------+----------+-------------+
|  1 | SIMPLE      | p     | NULL       | index  | NULL                                            | idx_person_first_name_last_name | 2046    | NULL        |  100 |   100.00 | Using index |
|  1 | SIMPLE      | e     | NULL       | eq_ref | uk_employee_person_id,fk_employee_membership_id | uk_employee_person_id           | 4       | qsuite.p.id |    1 |     5.00 | Using where |
+----+-------------+-------+------------+--------+-------------------------------------------------+---------------------------------+---------+-------------+------+----------+-------------+

Note the WHERE clause in the example doesn't end up actually filtering any rows.  This is largely representative of the data I have and the bulk of queries against this table.  Is there a way to coax MySQL into using that index or some not-quite-destructive way of restructuring this to improve the performance?

Thanks.

Edit: I dropped the original covering index and added one to each of the tables:

CREATE INDEX idx_person_id_first_name_last_name ON person ( id, first_name, last_name );
CREATE INDEX idx_employee_etc ON employee ( membership_id, type, enabled, person_id );

It seems to speed it up a little, but MySQL still insists on running through the employee table first:

+----+-------------+-------+------------+--------+--------------------------------------------+------------------+---------+--------------------+-------+----------+----------------------------------------------+
| id | select_type | table | partitions | type   | possible_keys                              | key              | key_len | ref                | rows  | filtered | Extra                                        |
+----+-------------+-------+------------+--------+--------------------------------------------+------------------+---------+--------------------+-------+----------+----------------------------------------------+
|  1 | SIMPLE      | e     | NULL       | ref    | uk_employee_person_id,idx_employee_etc     | idx_employee_etc | 68      | const,const,const  | 97311 |   100.00 | Using index; Using temporary; Using filesort |
|  1 | SIMPLE      | p     | NULL       | eq_ref | PRIMARY,idx_person_id_first_name_last_name | PRIMARY          | 4       | qsuite.e.person_id |     1 |   100.00 | NULL                                         |
+----+-------------+-------+------------+--------+--------------------------------------------+------------------+---------+--------------------+-------+----------+----------------------------------------------+

Body:
Storing first and last names redundantly in the employee table is an option - But with drawbacks. You will have to manage the redundancy. To guarantee the consistency, you can make those columns part of the foreign key. ON UPDATE CASCADE will take you some work. But you will still need to rewrite your INSERT statements or use triggers. With first_name and last_name being part of the employee table, you would be able to create an optimal index for your query. The table would look the following way:

CREATE TABLE employee (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    membership_id INTEGER NOT NULL,
    type VARCHAR(15),
    enabled BIT NOT NULL,
    person_id INTEGER NOT NULL REFERENCES person ( id ),
    CONSTRAINT fk_employee_membership_id FOREIGN KEY ( membership_id ) REFERENCES membership ( id ),
    CONSTRAINT fk_employee_person FOREIGN KEY ( person_id, first_name, last_name )
                                  REFERENCES person ( id, first_name, last_name ),
    INDEX (membership_id, type, enabled, first_name, last_name, person_id)
) engine=InnoDB;

The query would change to:

SELECT e.*
FROM employee e
WHERE e.membership_id = 1 AND e.type = 'INDIVIDUAL' AND e.enabled = 1
ORDER BY e.first_name ASC, e.last_name ASC, e.person_id ASC
LIMIT 100;

However - I would avoid such changes if possible. There might be other ways to use an index for ORDER BY. I would first try to move the WHERE conditions into a correlated EXISTS subquery:

SELECT e.*
FROM person p INNER JOIN employee e ON p.id = e.person_id
WHERE EXISTS (
  SELECT *
  FROM employee e1
  WHERE e1.person_id = p.id
    AND e1.membership_id = 1
    AND e1.type = 'INDIVIDUAL'
    AND e1.enabled = 1
)
ORDER BY p.first_name ASC, p.last_name ASC, p.id ASC
LIMIT 100;

Now, to evaluate the subquery, the engine needs p.id, so it has to start reading the data from person table first (which you will see in the execution plan). And I guess it will be smart enough to read it from the index. Note that in InnoDB the primary key is always part of any secondary key. So the idx_person_first_name_last_name index is actually on (first_name, last_name, id).


来源: stackexchange

问:
Where does credential management api store webauthn related data
WebAuthn includes an extension of the credential management api that allows you to work with public keys. I can go to the chrome settings and check managed passwords to see which username/passwords i have chosen to store in the browser using the credential management api. Few questions related to webauthn+credential management api combination.

What info does browser store when we successfully create a
credential?

Can we access this info from chrome settings (or some other way)?

答:
For your questions:

The browser does not store this information, the created information
(from an authenticator) is used for registering the authenticator to
the Reply Party

At runtime

ContentLicense: CC BY-SA 4.0


问:
how to filter the table so that it can give me only required values?
I want to filter data in sql
For example if i have 4 column
Project, technology, starttime and endtime

I want to filter my report when project and technology values are same in multiple rows then only select minimum value in starttime and maximum value in endtime

Can anyone tell me the query in sql to filter the table in this way
My query is

```<code>Select * from db.pro
Where Min(starttime) & Max(endtime)
Group by project, technology;
</code>```

答:
Looks like you want a basic GROUP BY:

```<code>select project, technology, Min(starttime), Max(endtime)
from db.pro
Group by project, technology;
</code>```

Body:
I want to filter data in sql
For example if i have 4 column
Project, technology, starttime and endtime

I want to filter my report when project and technology values are same in multiple rows then only select minimum value in starttime and maximum value in endtime

Can anyone tell me the query in sql to filter the table in this way
My query is

Select * from db.pro
Where Min(starttime) & Max(endtime)
Group by project, technology;

Body:
Looks like you want a basic GROUP BY:

select project, technology, Min(starttime), Max(endtime)
from db.pro
Group by project, technology;


问:
ASP.NET XML Parsing Error: no element found Line Number 1, Column 1 Error
Hey I found a weird temperamental page which randomly gives me the following error

```XML Parsing Error: no element found
Location: http://kj2011/site_2011/nonprofit-database/overview.aspx
Line Number 1, Column 1:```

This page was fine for like 2 weeks but as of yesterday I randomly get the above error. I was to delete the pages and recreate the error is gone but would come back again few hours later. I have some other templates

i.e http://kj2011/site_2011/nonprofit-database/financial.aspx

Which has the same Master File and User Controls but never gets the error just the overview.aspx  page.

Any Ideas ?

答: In my case it was the AjaxControlToolkit.dll that was missing from the bin folder. Adding a breakpoint in the Application_Error method in global.asax as suggested above allowed me to find this out.

ContentLicense: CC BY-SA 2.5

Body:
Hey I found a weird temperamental page which randomly gives me the following error

XML Parsing Error: no element found
Location: http://kj2011/site_2011/nonprofit-database/overview.aspx
Line Number 1, Column 1:

This page was fine for like 2 weeks but as of yesterday I randomly get the above error. I was to delete the pages and recreate the error is gone but would come back again few hours later. I have some other templates

i.e http://kj2011/site_2011/nonprofit-database/financial.aspx

Which has the same Master File and User Controls but never gets the error just the overview.aspx  page.

Any Ideas ?


问:
How to set properties in a custom HttpMessageHandler?
I am developing a cross-platform Xamarin Forms app, and I want to be able to use the platform-specific HttpMessageHandler subclasses AndroidClientHandler and NSUrlSessionHandler respectively, when I initialize the HttpClient object.

To accomplish this, I am configuring the Android and iOS app projects to use native HTTP client implementations, and then I use the parameterless constructor to initialize HttpClient:

```<code>var client = new HttpClient();
</code>```

However, I also would like to ensure that AllowAutoRedirect and UseCookies of the message handler are set to false. There is no Handler property in the HttpClient class. How can I ensure that these handler properties are correctly set in the implicitly initialized handler objects?

Since this is cross-platform code, I would like to avoid as much as possible to resort to using the HttpClient(HttpMessageHandler) constructor and explicitly pass in platform-specific handler instances. If at all possible, I would like to be able to pre-configure the properties of the handlers that are initialized in the parameterless constructor.

EDIT

From API documentation, it is easy to get the impression that the platform-specific handler implementations will be applied if you pass a HttpClientHandler object to the HttpClient constructor:

```<code>var handler = new HttpClientHandler
{
  AllowAutoRedirect = false,
  UseCookies = false
};
var client = new HttpClient(handler);
</code>```

Unfortunately, the above does not work in practice. With this approach, a HttpClientHandler object will be instantiated, regardless of whether HttpClient implementation has been set to native in the project settings.

In theory, one alternative would be if there was any way to obtain an instance of the handler that is initialized in the parameterless constructor, modify it and pass the modified instance into the HttpMessageHandler argument constructor, something like this:

```<code>var handler = GetHandlerInstanceAppliedInParameterlessHttpClientConstructor();
handler.AllowAutoRedirect = false;
handler.UseCookies = false;
var client = new HttpClient(handler);
</code>```

However, I am not aware of any method returning such a handler instance.

I should also point out that my main concern right now is Android, so an answer that applies primarily to Android might be enough.

答:
You don't need to expose the native handlers and implement it for both platforms. HttpClient accepts an overload with a handler, like you stated. However, that handler is a .NET Standard handler. So, if you initialise the handler in the shared project, or inherit from it in the native ones, they are the same type of class.

In your shared project, you can simply initialise the client like this:

var handler = new HttpClientHandler
{
    AllowAutoRedirect = false,
    UseCookies = false
};
var client = new HttpClient(handler);
```

However, this way you will override the "native" handler and will use HttpClientHandler instead.

Additional remarks, based on comments and edited question:

To answer your question - no, there isn'y any built-in way to get the AndroidClientHandler in the shared code. You'll have to expose it yourself. You can also write your own native handlers and expose them through a DependencyService and then invoke the ctor with them. The latter I have done in the past and it worked with no issues.

Body:
I am developing a cross-platform Xamarin Forms app, and I want to be able to use the platform-specific HttpMessageHandler subclasses AndroidClientHandler and NSUrlSessionHandler respectively, when I initialize the HttpClient object.

To accomplish this, I am configuring the Android and iOS app projects to use native HTTP client implementations, and then I use the parameterless constructor to initialize HttpClient:

var client = new HttpClient();

However, I also would like to ensure that AllowAutoRedirect and UseCookies of the message handler are set to false. There is no Handler property in the HttpClient class. How can I ensure that these handler properties are correctly set in the implicitly initialized handler objects?

Since this is cross-platform code, I would like to avoid as much as possible to resort to using the HttpClient(HttpMessageHandler) constructor and explicitly pass in platform-specific handler instances. If at all possible, I would like to be able to pre-configure the properties of the handlers that are initialized in the parameterless constructor.

EDIT

From API documentation, it is easy to get the impression that the platform-specific handler implementations will be applied if you pass a HttpClientHandler object to the HttpClient constructor:

var handler = new HttpClientHandler
{
  AllowAutoRedirect = false,
  UseCookies = false
};
var client = new HttpClient(handler);

Unfortunately, the above does not work in practice. With this approach, a HttpClientHandler object will be instantiated, regardless of whether HttpClient implementation has been set to native in the project settings.

In theory, one alternative would be if there was any way to obtain an instance of the handler that is initialized in the parameterless constructor, modify it and pass the modified instance into the HttpMessageHandler argument constructor, something like this:

var handler = GetHandlerInstanceAppliedInParameterlessHttpClientConstructor();
handler.AllowAutoRedirect = false;
handler.UseCookies = false;
var client = new HttpClient(handler);

However, I am not aware of any method returning such a handler instance.

I should also point out that my main concern right now is Android, so an answer that applies primarily to Android might be enough.

Body:
You don't need to expose the native handlers and implement it for both platforms. HttpClient accepts an overload with a handler, like you stated. However, that handler is a .NET Standard handler. So, if you initialise the handler in the shared project, or inherit from it in the native ones, they are the same type of class.

In your shared project, you can simply initialise the client like this:

var handler = new HttpClientHandler
{
    AllowAutoRedirect = false,
    UseCookies = false
};
var client = new HttpClient(handler);

However, this way you will override the "native" handler and will use HttpClientHandler instead.

Additional remarks, based on comments and edited question:

To answer your question - no, there isn'y any built-in way to get the AndroidClientHandler in the shared code. You'll have to expose it yourself. You can also write your own native handlers and expose them through a DependencyService and then invoke the ctor with them. The latter I have done in the past and it worked with no issues.


答:
Try like below. Please have look here to have more idea about how GROUP BY works.

```<code>Select project, technology, Min(starttime), Max(endtime)
from db.pro
Group by project, technology;
</code>```

Title: how to filter the table so that it can give me only required values?

Body:
Try like below. Please have look here to have more idea about how GROUP BY works.

Select project, technology, Min(starttime), Max(endtime)
from db.pro
Group by project, technology;


问:
How to get client ip from Google Network Load Balancer with kubernetes service
I created a kubernetes service in GKE with type:LoadBalancer.

apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: LoadBalancer
  ports:
  - name: http
    port: 80
    targetPort: http
  selector:
    app: nginx
```

<p>It's a nginx service and try to get origin client IP. like</p>

```        location / {
            echo $remote_addr;
            echo $http_x_forwarded_for;
        }
```

<p>But the result will get:</p>

```10.140.0.97

```

$remote_addr is like inside kubernetes IP.

$http_x_forwarded_for is empty.

I don't know why this is not like document said.

What I read

https://cloud.google.com/load-balancing/docs/network

Network Load Balancing is a pass-through load balancer, which means that your firewall rules must allow traffic from the client source IP addresses.

https://cloud.google.com/kubernetes-engine/docs/concepts/network-overview#ext-lb

If your Service needs to be reachable from outside the cluster and outside your VPC network, you can configure your Service as a LoadBalancer, by setting the Service's type field to LoadBalancer when defining the Service. GKE then provisions a Network Load Balancer in front of the Service. The Network Load Balancer is aware of all nodes in your cluster and configures your VPC network's firewall rules to allow connections to the Service from outside the VPC network, using the Service's external IP address. You can assign a static external IP address to the Service. Visit Configuring Domain Names with Static IP Addresses for more information.

答:
Just add externalTrafficPolicy: Local

spec:
  externalTrafficPolicy: Local
  type: LoadBalancer
```

Packets sent to Services with Type=LoadBalancer are source NAT’d by default, because all schedulable Kubernetes nodes in the Ready state are eligible for load-balanced traffic. So if packets arrive at a node without an endpoint, the system proxies it to a node with an endpoint, replacing the source IP on the packet with the IP of the node (as described in the previous section).

Reference

https://kubernetes.io/docs/tutorials/services/source-ip/#source-ip-for-services-with-typeloadbalancer

https://github.com/kubernetes/kubernetes/issues/10921

Body:
I created a kubernetes service in GKE with type:LoadBalancer.

apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: LoadBalancer
  ports:
  - name: http
    port: 80
    targetPort: http
  selector:
    app: nginx

It's a nginx service and try to get origin client IP. like

        location / {
            echo $remote_addr;
            echo $http_x_forwarded_for;
        }

But the result will get:

10.140.0.97

$remote_addr is like inside kubernetes IP.

$http_x_forwarded_for is empty.

I don't know why this is not like document said.

What I read

https://cloud.google.com/load-balancing/docs/network

Network Load Balancing is a pass-through load balancer, which means that your firewall rules must allow traffic from the client source IP addresses.

https://cloud.google.com/kubernetes-engine/docs/concepts/network-overview#ext-lb

If your Service needs to be reachable from outside the cluster and outside your VPC network, you can configure your Service as a LoadBalancer, by setting the Service's type field to LoadBalancer when defining the Service. GKE then provisions a Network Load Balancer in front of the Service. The Network Load Balancer is aware of all nodes in your cluster and configures your VPC network's firewall rules to allow connections to the Service from outside the VPC network, using the Service's external IP address. You can assign a static external IP address to the Service. Visit Configuring Domain Names with Static IP Addresses for more information.

Body:
Just add externalTrafficPolicy: Local

spec:
  externalTrafficPolicy: Local
  type: LoadBalancer

Packets sent to Services with Type=LoadBalancer are source NAT’d by default, because all schedulable Kubernetes nodes in the Ready state are eligible for load-balanced traffic. So if packets arrive at a node without an endpoint, the system proxies it to a node with an endpoint, replacing the source IP on the packet with the IP of the node (as described in the previous section).

Reference

https://kubernetes.io/docs/tutorials/services/source-ip/#source-ip-for-services-with-typeloadbalancer

https://github.com/kubernetes/kubernetes/issues/10921


问:
Read file with separation in C++
I have a script which reads text file into a vector.

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items
{
    string Name;
    int Number1;
    double Number2;
};

int main()
{
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (file >> player_info.Name >> player_info.Number1 >> player_info.Number2) {
        player_data.push_back(player_info);
    }

    for (auto &i : player_data) {
        std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}
</code>```

The file4.txt contains as follows:

```<code>Wogger Wabbit
2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8
</code>```

How can I display the data properly? How could I give the separation which is a line break ('\n')?

答:
You can solve your issue in the following way -

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items {
    string Name;
    int Number1;
    double Number2;
};

int main() {
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (getline(file,player_info.Name)) {
        file>>player_info.Number1>>player_info.Number2;
        player_data.push_back(player_info);
        file.ignore();

    }
    file.close();
    for (auto &i : player_data) {
        cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}
</code>```

Now let's investigate what's the catch is here.

First of all, your name can contain blank space between them and you can't take input a string with empty space using >> operator. You have to you getline() function to take input string with empty spaces. This function take input the whole line of the input file as a string.

Secondly, your other two inputs are integers or other primitive data types so you can take input them using >> operator. In the above code, these two input is inside the while loop.

Lastly and most important file.ignore(). >> operator terminates input when it encounters a blank space ' ', newline '\n' character. So after taking the input of player_info.Number2 there is a newline character in the input file so >> operator stop here but the newline character remains in the input buffer and getline() function is very sensitive to newline and blank space character so this creates a problem. So you have to somehow remove or ignore the buffer's newline character. file.ignore() do this job for you.

Title: Read file with separation in C++

Body:
I have a script which reads text file into a vector.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items
{
    string Name;
    int Number1;
    double Number2;
};

int main()
{
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (file >> player_info.Name >> player_info.Number1 >> player_info.Number2) {
        player_data.push_back(player_info);
    }

    for (auto &i : player_data) {
        std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}

The file4.txt contains as follows:

Wogger Wabbit
2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8

How can I display the data properly? How could I give the separation which is a line break ('\n')?

Body:
You can solve your issue in the following way -

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items {
    string Name;
    int Number1;
    double Number2;
};

int main() {
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (getline(file,player_info.Name)) {
        file>>player_info.Number1>>player_info.Number2;
        player_data.push_back(player_info);
        file.ignore();

    }
    file.close();
    for (auto &i : player_data) {
        cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}

Now let's investigate what's the catch is here.

First of all, your name can contain blank space between them and you can't take input a string with empty space using >> operator. You have to you getline() function to take input string with empty spaces. This function take input the whole line of the input file as a string.

Secondly, your other two inputs are integers or other primitive data types so you can take input them using >> operator. In the above code, these two input is inside the while loop.

Lastly and most important file.ignore(). >> operator terminates input when it encounters a blank space ' ', newline '\n' character. So after taking the input of player_info.Number2 there is a newline character in the input file so >> operator stop here but the newline character remains in the input buffer and getline() function is very sensitive to newline and blank space character so this creates a problem. So you have to somehow remove or ignore the buffer's newline character. file.ignore() do this job for you.


问:
How to make a variable that can be detected as multiple items
```<code>bot.on('message', msg=>{
   if(msg.content.includes(“hi” or? “hello” or? “hey”)){
      msg.reply(“hi” or? “hello” or? “hey”);
   }
})
</code>```

I’m coding a discord bot on my server and I want to add a feature where it responds to people. I want to make it so that my bot can detect multiple ways a user greets and have it greet them back.

答:
```<code>const greetings = {
"hi": "hi",
"hello":"hello"
.....
}

if (greetings[msg.content]) {}
</code>```

Body:
bot.on('message', msg=>{
   if(msg.content.includes(“hi” or? “hello” or? “hey”)){
      msg.reply(“hi” or? “hello” or? “hey”);
   }
})

I’m coding a discord bot on my server and I want to add a feature where it responds to people. I want to make it so that my bot can detect multiple ways a user greets and have it greet them back.


问:
Spring-data : How to query a subtype using a specification
I have three entites like this:

```<code>@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "TYPE")
public abstract class A
{
    // fields, getters, setters
}

@Entity
@DiscriminatorValue("B")
public class B extends A
{
    // fields, getters, setters
}

@Entity
@DiscriminatorValue("C")
public class C extends A
{
    // fields, getters, setters
}
</code>```

I also have a repository like this:

```<code>@Repository
public interface ADao extends JpaRepository<A, Long>, JpaSpecificationExecutor<A>
{
}
</code>```

On this repository, I have a method

```<code>List<A> findAll(Specification<A> s)
</code>```

which is defined in JpaSpecificationExecutor.

My question is:
how can I make a request using a specification on a field declared solely in B ?

Thanks in advance,
Jerome

答:
create a

```<code>@Repository public interface BDao extends ADao<B>{}
</code>```

and

```<code>public interface ADao extends JpaRepository<T extends A, Long>, JpaSpecificationExecutor<A>
</code>```

and then inject BDao to query B types

ContentLicense: CC BY-SA 3.0

Body:
I have three entites like this:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "TYPE")
public abstract class A
{
    // fields, getters, setters
}

@Entity
@DiscriminatorValue("B")
public class B extends A
{
    // fields, getters, setters
}

@Entity
@DiscriminatorValue("C")
public class C extends A
{
    // fields, getters, setters
}

I also have a repository like this:

@Repository
public interface ADao extends JpaRepository, JpaSpecificationExecutor
{
}

On this repository, I have a method

List findAll(Specification s)

which is defined in JpaSpecificationExecutor.

My question is:
how can I make a request using a specification on a field declared solely in B ?

Thanks in advance,
Jerome

Body:
create a

@Repository public interface BDao extends ADao<B>{}

and

public interface ADao extends JpaRepository<T extends A, Long>, JpaSpecificationExecutor<A>

and then inject BDao to query B types


问:
R fill in new column by filtered value by group
I want to create new column in my dat, filled in by values
satisfying a condition. So, I want to keep the value where where regime == "SA" and fill this value over the whole group in new column vals.sa.

This combines the filter and mutate, but I am unsure what is their correct combination? Filter just keeps rows satisfying condition, but how can I expand this value over all rows in a group?

My data:

```<code>dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "B", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))
</code>```

Process the data using dplyr

```<code>dat %>%
  # group data by id
  group_by(id) %>%
  # how to write this condition and get values instead or TRUE/FALSE?
  mutate(val.sa = regime == "SA")
</code>```

Expected output with filled in val.sa value corresponding regime == "SA"

```<code>     id regime value val.sa
  <dbl> <fct>  <dbl>  <dbl>
1     1 SA         3      3
2     1 B          5      3
3     2 SA         1      1
4     2 B          2      1
5     2 C          5      1
6     2 F          6      1
7     3 SA         7      7
8     3 D          8      7
</code>```

答:
In case you alwas have only one SA in each group, this should run without any errors:

```<code>dat %>%
  group_by(id) %>%
  mutate(val.sa = value[regime == "SA"])
#> # A tibble: 8 x 4
#> # Groups:   id [3]
#>      id regime value val.sa
#>   <dbl> <fct>  <dbl>  <dbl>
#> 1     1 SA         3      3
#> 2     1 B          5      3
#> 3     2 SA         1      1
#> 4     2 B          2      1
#> 5     2 C          5      1
#> 6     2 F          6      1
#> 7     3 SA         7      7
#> 8     3 D          8      7
</code>```

otherwise, you would have to decide which SA-value you would like to keep. For example always keeping the maximum value:

```<code>dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "SA", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))
dat
#>   id regime value
#> 1  1     SA     3
#> 2  1      B     5
#> 3  2     SA     1
#> 4  2     SA     2
#> 5  2      C     5
#> 6  2      F     6
#> 7  3     SA     7
#> 8  3      D     8

dat %>%
  group_by(id) %>%
  mutate(val.sa = max(value[regime == "SA"]))
#> # A tibble: 8 x 4
#> # Groups:   id [3]
#>      id regime value val.sa
#>   <dbl> <fct>  <dbl>  <dbl>
#> 1     1 SA         3      3
#> 2     1 B          5      3
#> 3     2 SA         1      2
#> 4     2 SA         2      2
#> 5     2 C          5      2
#> 6     2 F          6      2
#> 7     3 SA         7      7
#> 8     3 D          8      7
</code>```

Body:
I want to create new column in my dat, filled in by values
satisfying a condition. So, I want to keep the value where where regime == "SA" and fill this value over the whole group in new column vals.sa.

This combines the filter and mutate, but I am unsure what is their correct combination? Filter just keeps rows satisfying condition, but how can I expand this value over all rows in a group?

My data:

dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "B", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))

Process the data using dplyr

dat %>%
  # group data by id
  group_by(id) %>%
  # how to write this condition and get values instead or TRUE/FALSE?
  mutate(val.sa = regime == "SA")

Expected output with filled in val.sa value corresponding regime == "SA"

     id regime value val.sa
  <dbl> <fct>  <dbl>  <dbl>
1     1 SA         3      3
2     1 B          5      3
3     2 SA         1      1
4     2 B          2      1
5     2 C          5      1
6     2 F          6      1
7     3 SA         7      7
8     3 D          8      7

Body:
In case you alwas have only one SA in each group, this should run without any errors:

dat %>%
  group_by(id) %>%
  mutate(val.sa = value[regime == "SA"])
#> # A tibble: 8 x 4
#> # Groups:   id [3]
#>      id regime value val.sa
#>   <dbl> <fct>  <dbl>  <dbl>
#> 1     1 SA         3      3
#> 2     1 B          5      3
#> 3     2 SA         1      1
#> 4     2 B          2      1
#> 5     2 C          5      1
#> 6     2 F          6      1
#> 7     3 SA         7      7
#> 8     3 D          8      7

otherwise, you would have to decide which SA-value you would like to keep. For example always keeping the maximum value:

dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "SA", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))
dat
#>   id regime value
#> 1  1     SA     3
#> 2  1      B     5
#> 3  2     SA     1
#> 4  2     SA     2
#> 5  2      C     5
#> 6  2      F     6
#> 7  3     SA     7
#> 8  3      D     8

dat %>%
  group_by(id) %>%
  mutate(val.sa = max(value[regime == "SA"]))
#> # A tibble: 8 x 4
#> # Groups:   id [3]
#>      id regime value val.sa
#>   <dbl> <fct>  <dbl>  <dbl>
#> 1     1 SA         3      3
#> 2     1 B          5      3
#> 3     2 SA         1      2
#> 4     2 SA         2      2
#> 5     2 C          5      2
#> 6     2 F          6      2
#> 7     3 SA         7      7
#> 8     3 D          8      7


问:
React Hooks infinite loop with Array
I'm having an infinite loop when I assign an array to a state in a useEffect hook in React and I'm not sure why as I'm adding the state series as a dependency.

```<code>const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries([1, 2, 3, 4]);
}, [series]);
</code>```

The same code with a string doesn't create an infinite loop

```<code>const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries('No Infinite Loop');
}, [series]);
</code>```

答: [1,2,3]!==[1,2,3] while "123"==="123" when you set the array as a dependency and use THAT array as a state, the array "change" everything when setSeries which in turn trigger render in turn trigger useEffect which in turn trigger setSeries so on and so forth

Title: React Hooks infinite loop with Array

Body:
I'm having an infinite loop when I assign an array to a state in a useEffect hook in React and I'm not sure why as I'm adding the state series as a dependency.

const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries([1, 2, 3, 4]);
}, [series]);

The same code with a string doesn't create an infinite loop

const [series, setSeries] = useState([]);
useEffect(() => {
  setSeries('No Infinite Loop');
}, [series]);


问:
iOS - Broadcast Upload Extension - UserDidFinishSetup - pass parameters from Container app
I am developing an app using Broadcast Upload Extension - I would like to know how to pass parameters into the BroadcastViewController so I can them pass them onto the CompleteRequest method (userSetup parameter). Or am I suppose to reference the Container app somehow and get the parameters from there?

code from BroadcastViewController:

```<code>  public partial class BroadcastViewController : UIViewController
        {
            protected BroadcastViewController(IntPtr handle) : base(handle)
            {
                // Note: this .ctor should not contain any initialization logic.
            }

            public void UserDidFinishSetup()
            {
// NEED TO OBTAIN HERE PARAMETERS
                System.Diagnostics.Debug.WriteLine("ScreenShareExtensionUI: UserDidFinishSetup");
                // Broadcast url that will be returned to the application
                var broadcastURL = NSUrl.FromString("http://broadcastURL_example/stream1");

                // Service specific broadcast data example which will be supplied to the process extension during broadcast
                var keys = new[] { "channelName", "token", "appId" };
                var objects = new[] { "channelName", "token", "appId" };
                var setupInfo = NSDictionary.FromObjectsAndKeys(objects, keys);
</code>```

答:
I solved the issue by using App Groups capability. This allows me to fill in the parameters in the container app and then retrieve them in the extension like this:</p>

```<code>var plist = new NSUserDefaults("group.com.foo.ss", NSUserDefaultsType.SuiteName);
            var agoraApi = plist.StringForKey("agoraApi");
            var agoraRoomId = plist.DoubleForKey("agoraRoomId");
            var agoraToken = plist.StringForKey("agoraToken");
            var agoraUserId = plist.DoubleForKey("agoraUserId");
</code>```

Body:
I am developing an app using Broadcast Upload Extension - I would like to know how to pass parameters into the BroadcastViewController so I can them pass them onto the CompleteRequest method (userSetup parameter). Or am I suppose to reference the Container app somehow and get the parameters from there?

code from BroadcastViewController:

  public partial class BroadcastViewController : UIViewController
        {
            protected BroadcastViewController(IntPtr handle) : base(handle)
            {
                // Note: this .ctor should not contain any initialization logic.
            }

            public void UserDidFinishSetup()
            {
// NEED TO OBTAIN HERE PARAMETERS
                System.Diagnostics.Debug.WriteLine("ScreenShareExtensionUI: UserDidFinishSetup");
                // Broadcast url that will be returned to the application
                var broadcastURL = NSUrl.FromString("http://broadcastURL_example/stream1");

                // Service specific broadcast data example which will be supplied to the process extension during broadcast
                var keys = new[] { "channelName", "token", "appId" };
                var objects = new[] { "channelName", "token", "appId" };
                var setupInfo = NSDictionary.FromObjectsAndKeys(objects, keys);

Body:
I solved the issue by using App Groups capability. This allows me to fill in the parameters in the container app and then retrieve them in the extension like this:

var plist = new NSUserDefaults("group.com.foo.ss", NSUserDefaultsType.SuiteName);
            var agoraApi = plist.StringForKey("agoraApi");
            var agoraRoomId = plist.DoubleForKey("agoraRoomId");
            var agoraToken = plist.StringForKey("agoraToken");
            var agoraUserId = plist.DoubleForKey("agoraUserId");


问:
C++ do while loop menu
I have wrote a program to insert student names and displaying the list once name have inserted.The problem I am having is with the menu. When I input 1st value, message of system exiting displays. It's my first time writing a program for data structures and I am not familiar with the concepts. If you could correct me with where I went wrong will be helpful. Appreciate your response as I am stuck with this. See source code below. </p>

```<code>#include <iostream>
#include<string.h>
using namespace std;
struct node {
    string studentname;
    node* next;
};
bool isempty(node* head);
char menu();
void insertFirstElement(node*& head, node*& last, string studentname);
void insert(node *&head, node *&last, string studentname);
void remove(node*& head, node *&last);
void showlist(node* current);
int main()
{
    node* head = NULL;
    node* last = NULL;
    char choice;
    string name;

    do {
        choice = menu();
        switch (choice) {
        case 1:
            cout << "Please enter a student name : ";
            cin >> name;
            insert(head, last, name);
            break;
        case 2:
            remove(head, last);
            break;
        case 3:
            showlist(head);
            break;
        default :
            cout << "System is exiting" << endl;

        }
    } while (choice != 4);
}
bool isempty(node* head)
{
    if (head == NULL)
        return true;
    else
    return false;
}
char menu()
{
    char choice;
    cout << "1. Add a element" << endl;
    cout << "2. Remove an element" << endl;
    cout << "3. Display list" << endl;
    cout << "4. Exit" << endl;

    cin >> choice;
    return choice;
}
void insertFirstElement(node*& head, node*& last, string studentname)
{
    node* temp = new node;
    temp->studentname = studentname;
    temp->next = NULL;
    head = temp;
    last = temp;
}
void insert(node*& head, node*& last, string studentname)
{
    if (isempty(head)) {
        insertFirstElement(head, last, studentname);
    }
    else {
        node* temp = new node;
        temp->studentname = studentname;
        temp->next = NULL;
        last->next = temp;
        last = temp;
    }
}
void remove(node*& head, node*& last)
{
    if (isempty(head)) {
        cout << "The list is already empty" << endl;
    }
    else if (head == last) {
        delete head;
        head == NULL;
        last == NULL;
   }
    else {
        node* temp = head;
        head = head->next;
        delete temp;
    }
}
void showlist(node* current)
{
    if (isempty(current)) {
        cout << "The list is empty" << endl;
    }
    else {
        cout << "The list containts: \n";
        while (current != NULL) {
            cout << current->studentname << endl;
            current = current->next;
        }
    }
}
</code>```

答:
your choice variable is of type char and your function is returning a char, therefor your while condition should be

```<code>while (choice != '4');
</code>```

or you can change your function to type int and your variable to type int.

also you should be using NULLPTR instead of NULL

Title: C++ do while loop menu

Body:
I have wrote a program to insert student names and displaying the list once name have inserted.The problem I am having is with the menu. When I input 1st value, message of system exiting displays. It's my first time writing a program for data structures and I am not familiar with the concepts. If you could correct me with where I went wrong will be helpful. Appreciate your response as I am stuck with this. See source code below.

#include <iostream>
#include<string.h>
using namespace std;
struct node {
    string studentname;
    node* next;
};
bool isempty(node* head);
char menu();
void insertFirstElement(node*& head, node*& last, string studentname);
void insert(node *&head, node *&last, string studentname);
void remove(node*& head, node *&last);
void showlist(node* current);
int main()
{
    node* head = NULL;
    node* last = NULL;
    char choice;
    string name;

    do {
        choice = menu();
        switch (choice) {
        case 1:
            cout << "Please enter a student name : ";
            cin >> name;
            insert(head, last, name);
            break;
        case 2:
            remove(head, last);
            break;
        case 3:
            showlist(head);
            break;
        default :
            cout << "System is exiting" << endl;

        }
    } while (choice != 4);
}
bool isempty(node* head)
{
    if (head == NULL)
        return true;
    else
    return false;
}
char menu()
{
    char choice;
    cout << "1. Add a element" << endl;
    cout << "2. Remove an element" << endl;
    cout << "3. Display list" << endl;
    cout << "4. Exit" << endl;

    cin >> choice;
    return choice;
}
void insertFirstElement(node*& head, node*& last, string studentname)
{
    node* temp = new node;
    temp->studentname = studentname;
    temp->next = NULL;
    head = temp;
    last = temp;
}
void insert(node*& head, node*& last, string studentname)
{
    if (isempty(head)) {
        insertFirstElement(head, last, studentname);
    }
    else {
        node* temp = new node;
        temp->studentname = studentname;
        temp->next = NULL;
        last->next = temp;
        last = temp;
    }
}
void remove(node*& head, node*& last)
{
    if (isempty(head)) {
        cout << "The list is already empty" << endl;
    }
    else if (head == last) {
        delete head;
        head == NULL;
        last == NULL;
   }
    else {
        node* temp = head;
        head = head->next;
        delete temp;
    }
}
void showlist(node* current)
{
    if (isempty(current)) {
        cout << "The list is empty" << endl;
    }
    else {
        cout << "The list containts: \n";
        while (current != NULL) {
            cout << current->studentname << endl;
            current = current->next;
        }
    }
}

Body:
your choice variable is of type char and your function is returning a char, therefor your while condition should be

while (choice != '4');

or you can change your function to type int and your variable to type int.

also you should be using NULLPTR instead of NULL


问:
How do I stop local kentico project from taking up port localhost:8080
I installed Kentico and have been going through the tutorial. But I needed to work on another project and when trying to do so I was unable to as the Kentico project seems to be running on the localhost:8080 port.

I would like to restore localhost:8080 back to the way it was.

This is the error that I get when opening localhost:8080
localhost error screenshot

I have tried to enable directory browsing and trying to stop the process running on localhost:8080 but they did not work.

Any help would be much appreciated if anyone has any suggestions or has had to deal with something like this before.

答:
You can change the port of the websites in the applicationhost.config file for IIS Express.
Mine is located under '%userprofile%/Documents/IISExpress/Config'. </p>

<p>From there you can search for the 'sites' node. Look for your website and change the port number in the following line: </p>

```<code><binding protocol="http" bindingInformation=":8080:localhost" />
</code>```

Body:
You can change the port of the websites in the applicationhost.config file for IIS Express.
Mine is located under '%userprofile%/Documents/IISExpress/Config'.

From there you can search for the 'sites' node. Look for your website and change the port number in the following line:

<binding protocol="http" bindingInformation=":8080:localhost" />


问:
Trying to get latitude from Google Maps is returning null through intent in Android
I am trying to let the user select shipping address through google maps. The coordinates selected needs to be displayed in a text view. I'm using intents to return the selected coordinates to the previous activity but the problem is that no matter what I try the intent is returning null every time.

This is button click event that should put the coordinates inside the intent:

AddressSelectActivity.java

```<code>confirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent();
            intent.putExtra("Latitude", latitude);
            setResult(RESULT_OK, intent);

            finish();
        }
    });
</code>```

I'm retrieving the values onResume():

Register.java

```<code>shipping.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent mapsActivity = new Intent(v.getContext(), AddressSelectActivity.class);
            startActivityForResult(mapsActivity, 1);

        }
    });

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Toast.makeText(this, "Inside onActivityResult", Toast.LENGTH_SHORT).show();
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            Toast.makeText(this, data.getStringExtra("Latitude"), Toast.LENGTH_SHORT).show();
            shipping.setText(data.getStringExtra("Latitude"));
        }
    }
}
</code>```

Can anyone provide any guidance. Thank You!

答: You are not sending Intent anywhere, you just create Intent and call finish(). Even if you would send it, by calling startActivity, it would create another instance of Register activity. I suppose you do not want achieve that. To send data backwards check this post: How to pass data from 2nd activity to 1st activity when pressed back? - android</p>

Body:
I am trying to let the user select shipping address through google maps. The coordinates selected needs to be displayed in a text view. I'm using intents to return the selected coordinates to the previous activity but the problem is that no matter what I try the intent is returning null every time.

This is button click event that should put the coordinates inside the intent:

AddressSelectActivity.java

confirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent();
            intent.putExtra("Latitude", latitude);
            setResult(RESULT_OK, intent);

            finish();
        }
    });

I'm retrieving the values onResume():

Register.java

shipping.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent mapsActivity = new Intent(v.getContext(), AddressSelectActivity.class);
            startActivityForResult(mapsActivity, 1);

        }
    });

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Toast.makeText(this, "Inside onActivityResult", Toast.LENGTH_SHORT).show();
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            Toast.makeText(this, data.getStringExtra("Latitude"), Toast.LENGTH_SHORT).show();
            shipping.setText(data.getStringExtra("Latitude"));
        }
    }
}

Can anyone provide any guidance. Thank You!


问:
Import csv comma separated values into Table as multiple rows
I have a .csv file that looks something like this:

```<code>test1; A,B
test2; B
test3; A,B,C
</code>```

What I want is a table like:

```<code>test1  A
test1  B
test2  B
test3  A
test3  B
test3  C
</code>```

What I've already achieved:

```<code>LOAD DATA LOCAL INFILE 'path.csv'
INTO TABLE table1
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\n'
(col1, col2);
</code>```

But it skips all lines, that have multiple comma separated values in the second field...

I'm sorry, if this was already asked, but I'm completely struggling to find a solution for days...

答:
Consider the following. In part because I'm still using a rather old version of MySQL, I have a utility table of integers (ints) with values 0-9...</p>

```<code>DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(my_string VARCHAR(100) NOT NULL);

INSERT INTO my_table VALUES
('test1; A,B'),
('test2; B'),
('test3; A,B,C');

SELECT DISTINCT
       SUBSTRING_INDEX(my_string,';',1)  test
     , TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(my_string,';',-1),',',i+1),',',-1)) vals
  FROM my_table
     , ints;

+-------+------+
| test  | vals |
+-------+------+
| test1 | A    |
| test2 | B    |
| test3 | A    |
| test1 | B    |
| test3 | B    |
| test3 | C    |
+-------+------+
</code>```

Body:
I have a .csv file that looks something like this:

test1; A,B
test2; B
test3; A,B,C

What I want is a table like:

test1  A
test1  B
test2  B
test3  A
test3  B
test3  C

What I've already achieved:

LOAD DATA LOCAL INFILE 'path.csv'
INTO TABLE table1
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\n'
(col1, col2);

But it skips all lines, that have multiple comma separated values in the second field...

I'm sorry, if this was already asked, but I'm completely struggling to find a solution for days...

Body:
Consider the following. In part because I'm still using a rather old version of MySQL, I have a utility table of integers (ints) with values 0-9...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(my_string VARCHAR(100) NOT NULL);

INSERT INTO my_table VALUES
('test1; A,B'),
('test2; B'),
('test3; A,B,C');

SELECT DISTINCT
       SUBSTRING_INDEX(my_string,';',1)  test
     , TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(my_string,';',-1),',',i+1),',',-1)) vals
  FROM my_table
     , ints;

+-------+------+
| test  | vals |
+-------+------+
| test1 | A    |
| test2 | B    |
| test3 | A    |
| test1 | B    |
| test3 | B    |
| test3 | C    |
+-------+------+


问:
Make a link in the Android browser start up my app?
Is it possible to make a link such as:

```<code><a href="anton://useful_info_for_anton_app">click me!</a>
</code>```

cause my Anton app to start up?

I know that this works for the Android Market app with the market protocol, but can something similar be done with other apps?

Here is an example of a link that will start up the Android Market:

```<code><a href="market://search?q=pname:com.nytimes.android">click me!</a>
</code>```

Update:
The answer I accepted provided by eldarerathis works great, but I just want to mention that I had some trouble with the order of the subelements of the <intent-filter> tag. I suggest you simply make another <intent-filter> with the new subelements in that tag to avoid the problems I had. For instance my AndroidManifest.xml looks like this:

```<code><activity android:name=".AntonWorld"
          android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <data android:scheme="anton" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
</code>```

答:
This method doesn't call the disambiguation dialog asking you to open either your app or a browser.

If you register the following in your Manifest

```<code><manifest package="com.myApp" .. >
  <application ...>
    <activity ...>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
          android:host="gallery"
          android:scheme="myApp" />
      </intent-filter>
    </activity>
    ..
</code>```

and click this url from an email on your phone for example

```<code><a href="intent://gallery?directLink=true#Intent;scheme=myApp;package=com.myApp;end">
  Click me
</a>
</code>```

then android will try to find an app with the package com.myApp that responds to your gallery intent and has a myApp scheme. In case it can't, it will take you to the store, looking for com.myApp, which should be your app.

Body:
Is it possible to make a link such as:

click me!

cause my Anton app to start up?

I know that this works for the Android Market app with the market protocol, but can something similar be done with other apps?

Here is an example of a link that will start up the Android Market:

click me!

Update:
The answer I accepted provided by eldarerathis works great, but I just want to mention that I had some trouble with the order of the subelements of the <intent-filter> tag. I suggest you simply make another <intent-filter> with the new subelements in that tag to avoid the problems I had. For instance my AndroidManifest.xml looks like this:

<activity android:name=".AntonWorld"
          android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <data android:scheme="anton" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Body:
This method doesn't call the disambiguation dialog asking you to open either your app or a browser.

If you register the following in your Manifest

<manifest package="com.myApp" .. >
  <application ...>
    <activity ...>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
          android:host="gallery"
          android:scheme="myApp" />
      </intent-filter>
    </activity>
    ..

and click this url from an email on your phone for example

<a href="intent://gallery?directLink=true#Intent;scheme=myApp;package=com.myApp;end">
  Click me
</a>

then android will try to find an app with the package com.myApp that responds to your gallery intent and has a myApp scheme. In case it can't, it will take you to the store, looking for com.myApp, which should be your app.


问:
Replacing WooCommerce product Image using ACF custom fields
I'm trying to replace the  Image on WooCommerce Shop Page using hooks and advanced custom fields, but there something that I can not achieve:

The image I’m trying to evoke in my shop page is an image which I put in my custom content-single-product.php template, using ACF.

Here bellow is a copy of the code I used in my content-single-product.php to introduce the image 'prod_hero_second', that works, which I would like to use as a thumbnail in my shop page:

```<code><?php
$image = get_field('prod_hero_second');
if( !empty( $image ) ): ?>
    <img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>"
if( $image ): ?>
<p class="hero-caption"><?php echo esc_html($image['caption']); ?></p>
<?php endif; ?>
</code>```

How can I evoke this ACF prod_hero_second image into my shop page?

I tried to put the following code on my function.php but it does not work at all, no images appear on my shop page:

```<code>function replacing_template_loop_product_thumbnail() {
    // Remove product images from the shop loop
    remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
    // Adding something instead
    function wc_template_loop_product_replaced_thumb() {
        $image-> get_field ('prod_hero_second');
        echo $image;
    }
    add_action( 'woocommerce_before_shop_loop_item_title', 'wc_template_loop_product_replaced_thumb', 10 );
}
add_action( 'woocommerce_init', 'replacing_template_loop_product_thumbnail');
</code>```

But it doesn't work.

答:
It seems to me that I solved the issue.
My goal was to override the WooCommerce product image that is used by default in the shop page, used in the product 'grids, and which size is defined as woocommerce_thumbnail
My aim was to use a different image from my custom single-product.php template, the image named as field ’prod_hero_second’.

I found that this code works in my functions.php in order to override the default product image and use my custom ’prod_hero_second’ image as a woocommerce_thumbnail:

```<code>echo '<img src="'.get_field('prod_hero_second', $product_id)['url'].'" class="woocommerce_thumbnail">';
</code>```

I'm not so skilled to evaluate if this code is the most correct and effective, but I hope it can come as a valid solution.

Body:
I'm trying to replace the  Image on WooCommerce Shop Page using hooks and advanced custom fields, but there something that I can not achieve:

The image I’m trying to evoke in my shop page is an image which I put in my custom content-single-product.php template, using ACF.

Here bellow is a copy of the code I used in my content-single-product.php to introduce the image 'prod_hero_second', that works, which I would like to use as a thumbnail in my shop page:

<?php
$image = get_field('prod_hero_second');
if( !empty( $image ) ): ?>
    <img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>"
if( $image ): ?>

<?php echo esc_html($image['caption']); ?>

<?php endif; ?>

How can I evoke this ACF prod_hero_second image into my shop page?

I tried to put the following code on my function.php but it does not work at all, no images appear on my shop page:

function replacing_template_loop_product_thumbnail() {
    // Remove product images from the shop loop
    remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
    // Adding something instead
    function wc_template_loop_product_replaced_thumb() {
        $image-> get_field ('prod_hero_second');
        echo $image;
    }
    add_action( 'woocommerce_before_shop_loop_item_title', 'wc_template_loop_product_replaced_thumb', 10 );
}
add_action( 'woocommerce_init', 'replacing_template_loop_product_thumbnail');

But it doesn't work.

Body:
It seems to me that I solved the issue.
My goal was to override the WooCommerce product image that is used by default in the shop page, used in the product 'grids, and which size is defined as woocommerce_thumbnail
My aim was to use a different image from my custom single-product.php template, the image named as field ’prod_hero_second’.

I found that this code works in my functions.php in order to override the default product image and use my custom ’prod_hero_second’ image as a woocommerce_thumbnail:

echo '<img src="'.get_field('prod_hero_second', $product_id)['url'].'" class="woocommerce_thumbnail">';

I'm not so skilled to evaluate if this code is the most correct and effective, but I hope it can come as a valid solution.


问:
Should I expect POSIX to include getopt.h?
According to this, the POSIX library does not include getopt.h. However, I found this in unistd.h:

```<code>#ifdef  __USE_POSIX2
/* Get definitions and prototypes for functions to process the
   arguments in ARGV (ARGC of them, minus the program name) for
   options given in OPTS.  */
# define __need_getopt
# include <getopt.h>
#endif
</code>```

Does this mean that getopt.h is implicitly included when you include unistd.h? I mean, is the code above something I should expect from all implementations of the unistd header file, or is it just something that is in my particular version? Also, is the __USE_POSIX2 macro defined in POSIX.2 and onwards, or is it just for POSIX.2?

答:
getopt.h is not mentioned in the getopt(3) man page. If you need getopt, you should include unistd.h and define (assuming GLIBC) _XOPEN_SOURCE or _POSIX_C_SOURCE=something_greater_than_2 and not worry about the implementation details of the C library. Other environments might have different ways of turning on/off POSIX features.

Note that your tags imply the use of getopt_long. This is a GNU extension, and thus not portable.

Body:
According to this, the POSIX library does not include getopt.h. However, I found this in unistd.h:

#ifdef  __USE_POSIX2
/* Get definitions and prototypes for functions to process the
   arguments in ARGV (ARGC of them, minus the program name) for
   options given in OPTS.  */
# define __need_getopt
# include <getopt.h>
#endif

Does this mean that getopt.h is implicitly included when you include unistd.h? I mean, is the code above something I should expect from all implementations of the unistd header file, or is it just something that is in my particular version? Also, is the __USE_POSIX2 macro defined in POSIX.2 and onwards, or is it just for POSIX.2?


问:
Lazy load Google map
I want to Lazy Load Google Maps to get a better pageload-speed for SEO. My javascript works, but it still tries to load the map multiple times. How can i get it to load once? I found other scripts but i want to use as less code as possible.

My script:

```<code>google = false;
$(window).scroll(function() {
   var hT = $('#google-map').offset().top,
       hH = $('#google-map').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
        if (!google) $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
            initialize();
        });
   }
});
</code>```

Console log:

```<code>js?key={key}&_=1591085205888:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205888:140
js?key={key}&_=1591085205890:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205890:140
js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
</code>```

Thanks in advance!
Peter

答:
I think you are running the script over and over? Add a google = true after the if statement?

```<code>google = false;
$(window).scroll(function() {
   var hT = $('#google-map').offset().top,
       hH = $('#google-map').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
        if (!google) {
           google = true; // stop the check
           // enter your loading script here, use debounce and promise for async.
        }
   }
});
</code>```

Revised as per suggestion from musefan
You can also make it like

```<code>    var $googleMap = $('#google-map'); // use a ref
    var $window = $(window); // use a ref
    var google = false;

$(window).scroll(function() {
    var hT = $googleMap.offset().top,
        hH = $googleMap.outerHeight(),
        wH = $window.height(),
        wS = $window.scrollTop();
    if (wS > (hT+hH-wH)){
         // if you do the unregister approach, you dont even need to check for google var
        if (!google) {
            google = true; // stop the check
            // enter your loading script here, use debounce and promise for async.
        // unregister your event as musefan said
                    }
               }
            });
</code>```

Title: Lazy load Google map

Body:
I want to Lazy Load Google Maps to get a better pageload-speed for SEO. My javascript works, but it still tries to load the map multiple times. How can i get it to load once? I found other scripts but i want to use as less code as possible.

My script:

google = false;
$(window).scroll(function() {
   var hT = $('#google-map').offset().top,
       hH = $('#google-map').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
        if (!google) $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
            initialize();
        });
   }
});

Console log:

js?key={key}&_=1591085205888:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205888:140
js?key={key}&_=1591085205890:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205890:140
js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.

Thanks in advance!
Peter

Body:
I think you are running the script over and over? Add a google = true after the if statement?

google = false;
$(window).scroll(function() {
   var hT = $('#google-map').offset().top,
       hH = $('#google-map').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
        if (!google) {
           google = true; // stop the check
           // enter your loading script here, use debounce and promise for async.
        }
   }
});

Revised as per suggestion from musefan
You can also make it like

    var $googleMap = $('#google-map'); // use a ref
    var $window = $(window); // use a ref
    var google = false;

$(window).scroll(function() {
    var hT = $googleMap.offset().top,
        hH = $googleMap.outerHeight(),
        wH = $window.height(),
        wS = $window.scrollTop();
    if (wS > (hT+hH-wH)){
         // if you do the unregister approach, you dont even need to check for google var
        if (!google) {
            google = true; // stop the check
            // enter your loading script here, use debounce and promise for async.
        // unregister your event as musefan said
                    }
               }
            });


问:
How do I generate a index signature type with a number as key in TypeScript using quicktype?
I am currently trying to create TypeScript interfaces with quicktype and am now facing the challenge of generating a variable with a index signature type with a number as key.

I already managed to generate a variable with a index signature type and a string as key. It seems like this is the default behaviour, because I did not define string as key type.

This is the json schema:

```<code>{
    "$id": "Test",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Test",
    "definitions": {
        "A": {
            "type": "object",
            "properties": {
                "x": {
                    "type": "integer"
                }
            }
        }
    },
    "type": "object",
    "properties": {
        "mapA": {
            "type": "object",
            "additionalProperties": {
                "$ref": "#/definitions/A"
            }
        }
    },
    "required": [
        "mapA"
    ]
}
</code>```

And these are the generated TypeScript interfaces:

```<code>export interface Test {
    mapA: { [key: string]: A };
}

export interface A {
    x?: number;
}
</code>```

Can anybody tell me if it is possible to generate a index signature type with a number as key like this:

```<code>export interface Test {
    mapA: { [key: number]: A };
}
</code>```

Thans for your help!

答:
Official comment of quicktype team:

JSON does not allow number maps, so we cannot support it.

Body:
I am currently trying to create TypeScript interfaces with quicktype and am now facing the challenge of generating a variable with a index signature type with a number as key.

I already managed to generate a variable with a index signature type and a string as key. It seems like this is the default behaviour, because I did not define string as key type.

This is the json schema:

{
    "$id": "Test",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Test",
    "definitions": {
        "A": {
            "type": "object",
            "properties": {
                "x": {
                    "type": "integer"
                }
            }
        }
    },
    "type": "object",
    "properties": {
        "mapA": {
            "type": "object",
            "additionalProperties": {
                "$ref": "#/definitions/A"
            }
        }
    },
    "required": [
        "mapA"
    ]
}

And these are the generated TypeScript interfaces:

export interface Test {
    mapA: { [key: string]: A };
}

export interface A {
    x?: number;
}

Can anybody tell me if it is possible to generate a index signature type with a number as key like this:

export interface Test {
    mapA: { [key: number]: A };
}

Thans for your help!


问:
Does Azure Blob Storage supports partial content 206 by default?
I am using Azure blob storage to storage all my images and videos. I have implemented the upload and fetch functionality and it's working quite good. I am facing 1 issue while loading the videos, because when I use the url which is generated after uploading that video on Azure blob storage, it's downloading all the content first before rendering it to the user. So if the video size is 100 mb, it'll download all the 100 mb and till than user won't able to see the video.

I have done a lot of R&D and came to know that while rendering the video, I need to fetch the partial content (status 206) rather than fetching the whole video at a time. After adding the request header "Range:bytes-500", I tried to hit the blog url, but it's still downloading the whole content. So I have checked with some open source video URLs and tried to hit the video URL along with the "Range" request header and it was successfully giving 206 response status, which means it was properly giving me the partial content instead of the full video.

I read some forum and they are saying Azure storage supports the partial content concept and need to enable it from the properties. But I have checked all the options under the Azure storage account but didn't find anything to enable this functionality.

Can anyone please help me out to resolve this or if there's anything on Azure portal that I need to enable? It's something that I have been doing the R&D for this since a week now. Any help would be really appreciated.

Thank you! Stay safe.

答:
Suppose the Accept-Ranges is not enabled, from this blog I got it needs to set the default version of the service.

Below is a sample code to implement it.

```<code>            var credentials = new StorageCredentials("account name", "account key");
            var account = new CloudStorageAccount(credentials, true);
            var client = account.CreateCloudBlobClient();
            var properties = client.GetServiceProperties();
            properties.DefaultServiceVersion = "2019-07-07";
            client.SetServiceProperties(properties);
</code>```

Below is a return header comparison after setting the property.

Before:

After:

Body:
Suppose the Accept-Ranges is not enabled, from this blog I got it needs to set the default version of the service.

Below is a sample code to implement it.

            var credentials = new StorageCredentials("account name", "account key");
            var account = new CloudStorageAccount(credentials, true);
            var client = account.CreateCloudBlobClient();
            var properties = client.GetServiceProperties();
            properties.DefaultServiceVersion = "2019-07-07";
            client.SetServiceProperties(properties);

Below is a return header comparison after setting the property.

Before:

After:


问:
Change in predicted logit in logistic regression with splines depending on other values of the same variable in the data frame
I've run the following model:

```<code>log <- svyglm(compo ~ bs(edadc,degree=1, knots =c(-1,8)) +
  numenf5 + BMIc + BMIc2 + fried,
  dclus,family = quasibinomial)
</code>```

When I try to calculate logits for edadc=0, I get different results when I write:

```<code>newdata2 <- with(compoc,
  data.frame(edadc = rep(seq(from = -1, to = 0))))
newdata2$BMIc<-0
newdata2$BMIc2<-0
newdata2$numenf5<-2
newdata2$fried<-"R"
newdata2 <- cbind(newdata2, predict(log, newdata2,
      type = "link",se= TRUE))

 edadc BMIc BMIc2 numenf5 fried       link        SE
1    -1    0     0       2     R -0.8689483 0.1319695
2     0    0     0       2     R -0.2217048 0.1569442
</code>```

and when I write:

```<code>newdata2 <- with(compoc,
 data.frame(edadc = rep(seq(from = -1, to = 1))))
newdata2$BMIc<-0
newdata2$BMIc2<-0
newdata2$numenf5<-2
newdata2$fried<-"R"
newdata2 <- cbind(newdata2, predict(log,
    newdata2, type = "link",se= TRUE))

 edadc BMIc BMIc2 numenf5 fried       link        SE
1    -1    0     0       2     R -0.8689483 0.1319695
2     0    0     0       2     R -0.5453266 0.1021396
3     1    0     0       2     R -0.2217048 0.1569442
</code>```

The different calculation for link happens when I introduce positive values for edadc in newdata2.

答:
At request of Ben Bolker, here you have a reproducible example:</p>

```<code>library(survey)
library(splines)
data(api)
apiclus2$dep<-ifelse(apiclus2$api00<=800, 1, 0)
apiclus2$ellc<-apiclus2$ell-15
dclus <- svydesign(id=~dnum,data=apiclus2)
log<-svyglm(dep ~  bs(ellc,degree=1, knots =c(-1,8)) , dclus,family = quasibinomial)
summary(log)
newdata <- data.frame(ellc = 0)
newdata <- cbind(newdata, predict(log, newdata, type = "link",se= TRUE))
#link for ellc=0-->2.029313
newdata2 <- data.frame(ellc = rep(seq(from = -15, to = 51)))
newdata2 <- cbind(newdata2, predict(log, newdata = newdata2, type = "link",se= TRUE))
#link for ellc=0-->1.53011523
newdata2 <- data.frame(ellc = rep(seq(from = -15, to = 0)))
newdata2 <- cbind(newdata2, predict(log, newdata = newdata2, type = "link",se= TRUE))
#link for ellc=0-->2.02931340
newdata2 <- data.frame(ellc = rep(seq(from = -15, to = 1)))
newdata2 <- cbind(newdata2, predict(log, newdata = newdata2, type = "link",se= TRUE))
#link for ellc=0-->1.74851443
</code>```

Body:
I've run the following model:

log <- svyglm(compo ~ bs(edadc,degree=1, knots =c(-1,8)) +
  numenf5 + BMIc + BMIc2 + fried,
  dclus,family = quasibinomial)

When I try to calculate logits for edadc=0, I get different results when I write:

newdata2 <- with(compoc,
  data.frame(edadc = rep(seq(from = -1, to = 0))))
newdata2$BMIc<-0
newdata2$BMIc2<-0
newdata2$numenf5<-2
newdata2$fried<-"R"
newdata2 <- cbind(newdata2, predict(log, newdata2,
      type = "link",se= TRUE))

 edadc BMIc BMIc2 numenf5 fried       link        SE
1    -1    0     0       2     R -0.8689483 0.1319695
2     0    0     0       2     R -0.2217048 0.1569442

and when I write:

newdata2 <- with(compoc,
 data.frame(edadc = rep(seq(from = -1, to = 1))))
newdata2$BMIc<-0
newdata2$BMIc2<-0
newdata2$numenf5<-2
newdata2$fried<-"R"
newdata2 <- cbind(newdata2, predict(log,
    newdata2, type = "link",se= TRUE))

 edadc BMIc BMIc2 numenf5 fried       link        SE
1    -1    0     0       2     R -0.8689483 0.1319695
2     0    0     0       2     R -0.5453266 0.1021396
3     1    0     0       2     R -0.2217048 0.1569442

The different calculation for link happens when I introduce positive values for edadc in newdata2.

Body:
At request of Ben Bolker, here you have a reproducible example:

library(survey)
library(splines)
data(api)
apiclus2$dep<-ifelse(apiclus2$api00<=800, 1, 0)
apiclus2$ellc<-apiclus2$ell-15
dclus <- svydesign(id=~dnum,data=apiclus2)
log<-svyglm(dep ~  bs(ellc,degree=1, knots =c(-1,8)) , dclus,family = quasibinomial)
summary(log)
newdata <- data.frame(ellc = 0)
newdata <- cbind(newdata, predict(log, newdata, type = "link",se= TRUE))
#link for ellc=0-->2.029313
newdata2 <- data.frame(ellc = rep(seq(from = -15, to = 51)))
newdata2 <- cbind(newdata2, predict(log, newdata = newdata2, type = "link",se= TRUE))
#link for ellc=0-->1.53011523
newdata2 <- data.frame(ellc = rep(seq(from = -15, to = 0)))
newdata2 <- cbind(newdata2, predict(log, newdata = newdata2, type = "link",se= TRUE))
#link for ellc=0-->2.02931340
newdata2 <- data.frame(ellc = rep(seq(from = -15, to = 1)))
newdata2 <- cbind(newdata2, predict(log, newdata = newdata2, type = "link",se= TRUE))
#link for ellc=0-->1.74851443