问:
How to select unique pairs in SQL Server according to the third parameter?
I have the test table with three columns Fir, Sec and Val.

```<code>Fir    Sec     Val
------------------
A       A       1
A       B       7
A       C       31
B       A       3
B       D       4
B       F       7
C       X       10
C       Y       10
C       Z       9
</code>```

I am trying to extract all the unique values of Fir with a minimum alphabetical value of Sec which corresponds to the maximum value of Val.

For a given text table, the output must be

```<code>Fir    Sec
----------
A       C
B       F
C       X
</code>```

I manage this somehow with the script below, but I think there should be an simpler solution to produce the same result.

SELECT
    Fir, MIN(Sec) AS Sec
FROM
    (SELECT
         a.Fir, b.Sec, MaxVal
     FROM
         (SELECT
              Fir, MAX(Val) AS MaxVal
          FROM
              Test3
          GROUP BY
              Fir) a
     LEFT OUTER JOIN
         Test3 b ON a.Fir = b.Fir AND a.MaxVal = b.Val) c
GROUP BY
    Fir
ORDER BY
    Fir
```

<p>Any suggestion to improve this would be appreciated.</p>

<p>Code to generate sample data:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE Test3
(
    Fir CHAR(5),
    Sec CHAR(5),
    Val INT
)

INSERT INTO Test3
VALUES ('A', 'A', 1), ('A', 'B', 7), ('A', 'C', 31),
       ('B', 'A', 3), ('B', 'D', 4), ('B', 'F', 7),
       ('C', 'X', 10), ('C', 'Y', 10), ('C', 'Z', 9)
</code>```

答:
You achieve the same by using INNER JOIN

```<code>SELECT M.FIR,MIN(SEC) FROM TEST3 M
INNER JOIN (
SELECT  FIR,MAX(VAL) SECC FROM TEST3 GROUP BY FIR) S ON S.SECC=M.VAL AND S.FIR=M.FIR
GROUP BY M.FIR
</code>```

Body:
I have the test table with three columns Fir, Sec and Val.

Fir    Sec     Val
------------------
A       A       1
A       B       7
A       C       31
B       A       3
B       D       4
B       F       7
C       X       10
C       Y       10
C       Z       9

I am trying to extract all the unique values of Fir with a minimum alphabetical value of Sec which corresponds to the maximum value of Val.

For a given text table, the output must be

Fir    Sec
----------
A       C
B       F
C       X

I manage this somehow with the script below, but I think there should be an simpler solution to produce the same result.

SELECT
    Fir, MIN(Sec) AS Sec
FROM
    (SELECT
         a.Fir, b.Sec, MaxVal
     FROM
         (SELECT
              Fir, MAX(Val) AS MaxVal
          FROM
              Test3
          GROUP BY
              Fir) a
     LEFT OUTER JOIN
         Test3 b ON a.Fir = b.Fir AND a.MaxVal = b.Val) c
GROUP BY
    Fir
ORDER BY
    Fir

Any suggestion to improve this would be appreciated.

Code to generate sample data:

CREATE TABLE Test3
(
    Fir CHAR(5),
    Sec CHAR(5),
    Val INT
)

INSERT INTO Test3
VALUES ('A', 'A', 1), ('A', 'B', 7), ('A', 'C', 31),
       ('B', 'A', 3), ('B', 'D', 4), ('B', 'F', 7),
       ('C', 'X', 10), ('C', 'Y', 10), ('C', 'Z', 9)

Body:
You achieve the same by using INNER JOIN

SELECT M.FIR,MIN(SEC) FROM TEST3 M
INNER JOIN (
SELECT  FIR,MAX(VAL) SECC FROM TEST3 GROUP BY FIR) S ON S.SECC=M.VAL AND S.FIR=M.FIR
GROUP BY M.FIR


来源: stackexchange

问:
How can I view the allocation unit size of a NTFS partition in Vista?
Which built in (if any) tool can I use to determine the allocation unit size of a certain NTFS partition ?</p>

答:
Easiest way, confirmed on 2012r2.

Go to "This PC"

Right click on the Disk

Click on Format

Under drop down "allocation unit size" will be the value of what the Allocation of the Unit size disk already is.

OwnerDisplayName: Jens

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Running Flask app in debug mode does not provide the IP or the Debugger PIN or any Request details
I am working on a Flask app, and at first the debug mode was working as expected. It typically had an output such as "Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)" and the Request Status Codes everytime I made any changes and also provided a debugger PIN.
After making a few changes and re-organizing my App file structure by adding Blueprints, these details do not come up in the command line while running the App.

The output is always just this

```<code>Serving Flask app "web_app" (lazy loading)
 * Environment: development
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
</code>```

Instead of the previous output, that contained the IP, Debugger PIN etc.

```<code>* Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 139-055-956
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
</code>```

I can't figure out why this is happening.The changes I made were adding Blueprints and moving a few routes into them, and the initialization of the App was made through an function.

The name of the app is "web_app"

My run.py

```<code>from web_app import create_app
app = create_app()

if __name__ == '__main__':
    app.run(debug=True)
</code>```

web_app.init.py

```<code>from flask import Flask
from web_app.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

db = SQLAlchemy()
bcrypt = Bcrypt()
login = LoginManager()
mail = Mail()

def create_app(config_class = Config):
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app)
    from web_app.models import User, Retailer, Results, Watchlist
    with app.app_context():
        db.create_all()
    bcrypt.init_app(app)
    login.init_app(app)
    mail.init_app(app)
    from web_app.main.routes import main
    from web_app.posts.routes import post
    from web_app.user.routes import user
    from web_app.errors.handlers import errors
    app.register_blueprint(main)
    app.register_blueprint(post)
    app.register_blueprint(user)
    app.register_blueprint(errors)
    login.login_view = 'user.login'
    return app
</code>```

config.py

```<code>import os

class Config:
    SECRET_KEY = '5ab34f90107c5d025461e91c2d6ce13d'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///test1.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    MAIL_SERVER = 'smtp.gmail.com'
    MAIL_PORT = 587
    MAIL_USE_TLS = True
    MAIL_USERNAME = os.environ.get('EMAIL_USER')
    MAIL_PASSWORD = os.environ.get('EMAIL_PASS')
</code>```

I don't know if I have provided enough info for this, please let me know if anything is required.

Thanks in advance!

答:
figured out what the issue was. One of my programs associated with this was using the built-in logging module and all the data was being logged to the log file. Once I removed the log file, and changed the logging config, it started working correctly.
:)</p>

Body:
I am working on a Flask app, and at first the debug mode was working as expected. It typically had an output such as "Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)" and the Request Status Codes everytime I made any changes and also provided a debugger PIN.
After making a few changes and re-organizing my App file structure by adding Blueprints, these details do not come up in the command line while running the App.

The output is always just this

Serving Flask app "web_app" (lazy loading)
 * Environment: development
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on

Instead of the previous output, that contained the IP, Debugger PIN etc.

* Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 139-055-956
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

I can't figure out why this is happening.The changes I made were adding Blueprints and moving a few routes into them, and the initialization of the App was made through an function.

The name of the app is "web_app"

My run.py

from web_app import create_app
app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

web_app.init.py

from flask import Flask
from web_app.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

db = SQLAlchemy()
bcrypt = Bcrypt()
login = LoginManager()
mail = Mail()

def create_app(config_class = Config):
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app)
    from web_app.models import User, Retailer, Results, Watchlist
    with app.app_context():
        db.create_all()
    bcrypt.init_app(app)
    login.init_app(app)
    mail.init_app(app)
    from web_app.main.routes import main
    from web_app.posts.routes import post
    from web_app.user.routes import user
    from web_app.errors.handlers import errors
    app.register_blueprint(main)
    app.register_blueprint(post)
    app.register_blueprint(user)
    app.register_blueprint(errors)
    login.login_view = 'user.login'
    return app

config.py

import os

class Config:
    SECRET_KEY = '5ab34f90107c5d025461e91c2d6ce13d'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///test1.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    MAIL_SERVER = 'smtp.gmail.com'
    MAIL_PORT = 587
    MAIL_USE_TLS = True
    MAIL_USERNAME = os.environ.get('EMAIL_USER')
    MAIL_PASSWORD = os.environ.get('EMAIL_PASS')

I don't know if I have provided enough info for this, please let me know if anything is required.

Thanks in advance!


问:
How to peek at STDIN with Delphi 7?
In a Delphi 7 console application, how can I check whether stdin holds a character, without blocking until one is entered?

My plan is that this console program will be executed by a GUI program, and its stdin will be written to by the GUI program.

So I want my console app to periodically check stdin, but I can't find a way of doing this without blocking.

I have looked at this answer, which gets me a stream pointing to stdin, but there's still no way to "peek" as far as I can see.

答:
I think you have already found the right way to read stdin. It is meant to block when there's nothing more to be read.

The standard way to handle this is to use a separate thread to handle the pipe. When it receives new data from stdin it signals this to the processing thread, for example with a message passing mechanism.

Having said all that, if you really want to poll you can call PeekNamedPipe to check if there is data in the pipe.

ContentLicense: CC BY-SA 3.0

Title: How to peek at STDIN with Delphi 7?


问:
Why is get_current_user_id() returning 0 when used in woocommerce_login_redirect hook
I was searching now for a while to find a solution for my problem, where the function get_current_user_id() returns 0 when hooked to woocommerce_login_redirect.
Right after the login-redirect there should always be an user-id, or am I getting s.th wrong here?

In my function.php file I have follwoing code:

```<code>add_action( 'woocommerce_login_redirect', 'ffaces_register_customer' );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer' );

function ffaces_register_customer( $user ) {

  $customerid = get_current_user_id();

  if ( $customerid == 0 ) {
    $redirection_url = get_permalink( wc_get_page_id( 'myaccount' ) );
    return $redirection_url;
    exit();
  }

  // more code working with $customerid

  return home_url("my-account/my-projects");
  exit();
}
</code>```

答:
I don't think its set yet when this fires.

The hook passes the user object of the user that logged in try to change

$customerid = get_current_user_id();

to

$customerid = $user->ID;

Body:
I was searching now for a while to find a solution for my problem, where the function get_current_user_id() returns 0 when hooked to woocommerce_login_redirect.
Right after the login-redirect there should always be an user-id, or am I getting s.th wrong here?

In my function.php file I have follwoing code:

add_action( 'woocommerce_login_redirect', 'ffaces_register_customer' );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer' );

function ffaces_register_customer( $user ) {

  $customerid = get_current_user_id();

  if ( $customerid == 0 ) {
    $redirection_url = get_permalink( wc_get_page_id( 'myaccount' ) );
    return $redirection_url;
    exit();
  }

  // more code working with $customerid

  return home_url("my-account/my-projects");
  exit();
}


问:
Form field value doesn't post
I am fetching some values from a table using

```<code>$match = $wpdb->get_results("SELECT * FROM $tablename WHERE approve = 0");
</code>```

In the database all fields are set to text and 'latin1_swedish_ci' collation.

I then insert these into input fields:

```<code><input type="hidden" name="tID" value="<?php echo $row->id ?>">
<input type="hidden" name="first" value="<?php echo $match[0]->team_one ?>">
<input type="hidden" name="second" value="<?php echo $match[0]->second ?>">
<input type="hidden" name="winner" value="<?php echo $match[0]->winner ?>">
</code>```

https://i.stack.imgur.com/0Eo3G.png

Then I'm retrieving all the values when I click the submit button using:

```<code>$tID = $wpdb->escape($_POST['tID']);
$first = $wpdb->escape($_POST['first']);
$second = $wpdb->escape($_POST['second']);
$win = $wpdb->escape($_POST['winner']);
</code>```

The issue is that whenever I have the input field with a value of "$match[0]->second", on submit it always refreshes the page and says the same page cannot be found (error 404)!! also I can never retrieve the value of $second. Any other value is fine but just not second..

答: the issue was the input field had a "name" of "second" which for some reason caused a lot of bugs. Changing the name fixed the issue</p>

Title: Form field value doesn't post

Body:
I am fetching some values from a table using

$match = $wpdb->get_results("SELECT * FROM $tablename WHERE approve = 0");

In the database all fields are set to text and 'latin1_swedish_ci' collation.

I then insert these into input fields:

<input type="hidden" name="tID" value="<?php echo $row->id ?>">
<input type="hidden" name="first" value="<?php echo $match[0]->team_one ?>">
<input type="hidden" name="second" value="<?php echo $match[0]->second ?>">
<input type="hidden" name="winner" value="<?php echo $match[0]->winner ?>">

https://i.stack.imgur.com/0Eo3G.png

Then I'm retrieving all the values when I click the submit button using:

$tID = $wpdb->escape($_POST['tID']);
$first = $wpdb->escape($_POST['first']);
$second = $wpdb->escape($_POST['second']);
$win = $wpdb->escape($_POST['winner']);

The issue is that whenever I have the input field with a value of "$match[0]->second", on submit it always refreshes the page and says the same page cannot be found (error 404)!! also I can never retrieve the value of $second. Any other value is fine but just not second..


问:
Sending Message to Multiple Numbers using Intent
Hi i have a list of numbers.

```<code>ArrayList<String> numbers;
</code>```

I want to sent message to all these number using Intent, together .
I did this with email like sending email to multiple people , How to do for message ?

```<code>public static void send(Context ctx, String[] addy, String subject,
        String body,File attachment) {
    try {
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.setType("vnd.android-dir/mms-sms");
        sendIntent.putExtra(android.content.Intent.EXTRA_PHONE_NUMBER,
                addy);
        sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
        sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
        //sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(attachment));
        ctx.startActivity(Intent.createChooser(sendIntent,
                "Send via which Application?"));
    } catch (Exception e) {
        Toast.makeText(ctx, "No activity was found to handle this action",
                Toast.LENGTH_SHORT).show();
    }
}
</code>```

This is opening the message app but the numbers stored in addy are not listed in message sent to column

答:
for java developer use

```<code>public static void send(Context ctx, String[] address, String subject,
                        String body, File attachment) {

    List<String> mylist = Arrays.asList(address);
    Intent sendIntent = new Intent(Intent.ACTION_VIEW);

    StringJoiner sj = new StringJoiner(";", "smsto:", "");
    mylist.forEach(sj::add);
    sendIntent.setData(Uri.parse(sj.toString()));

    sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);

    if(sendIntent.resolveActivity(ctx.getPackageManager()) != null) {
        ctx.startActivity(sendIntent);
    }
}
</code>```

for those using kotlin, use

```<code>fun send(ctx: Context, address: Array<String>, subject: String, body: String, attachment: File) {

    val sendIntent = Intent(Intent.ACTION_VIEW)

    val data = address.toList().joinToString(";", "smsto:")

    sendIntent.data = Uri.parse(data)
    sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject)
    sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, body)

    if(sendIntent.resolveActivity(ctx.packageManager) != null) {
        ctx.startActivity(sendIntent)
    }
}
</code>```

Body:
Hi i have a list of numbers.

ArrayList<String> numbers;

I want to sent message to all these number using Intent, together .
I did this with email like sending email to multiple people , How to do for message ?

public static void send(Context ctx, String[] addy, String subject,
        String body,File attachment) {
    try {
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.setType("vnd.android-dir/mms-sms");
        sendIntent.putExtra(android.content.Intent.EXTRA_PHONE_NUMBER,
                addy);
        sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
        sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
        //sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(attachment));
        ctx.startActivity(Intent.createChooser(sendIntent,
                "Send via which Application?"));
    } catch (Exception e) {
        Toast.makeText(ctx, "No activity was found to handle this action",
                Toast.LENGTH_SHORT).show();
    }
}

This is opening the message app but the numbers stored in addy are not listed in message sent to column

Body:
for java developer use

public static void send(Context ctx, String[] address, String subject,
                        String body, File attachment) {

    List<String> mylist = Arrays.asList(address);
    Intent sendIntent = new Intent(Intent.ACTION_VIEW);

    StringJoiner sj = new StringJoiner(";", "smsto:", "");
    mylist.forEach(sj::add);
    sendIntent.setData(Uri.parse(sj.toString()));

    sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);

    if(sendIntent.resolveActivity(ctx.getPackageManager()) != null) {
        ctx.startActivity(sendIntent);
    }
}

for those using kotlin, use

fun send(ctx: Context, address: Array<String>, subject: String, body: String, attachment: File) {

    val sendIntent = Intent(Intent.ACTION_VIEW)

    val data = address.toList().joinToString(";", "smsto:")

    sendIntent.data = Uri.parse(data)
    sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject)
    sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, body)

    if(sendIntent.resolveActivity(ctx.packageManager) != null) {
        ctx.startActivity(sendIntent)
    }
}


问:
Why is geom_bar not splitting categorical variables
Very new to R programming and trying to create a bar plot, however my categorical x variable remains grouped together and I get a single bar without any usable information. A subsample is as follows:

```<code>     New Name Tot Pl L Ld P Min
 1:        1   376.62     5.91
 2:        4   689.07     7.26
 3:        5   202.14     4.67
 4:        6   516.28     6.01
 5:        7   698.02     7.41
 6:        8   180.50     3.69
 7:        9   163.12     4.24
 8:       10   176.66     4.59
 9:       11   665.34     7.97
10:        2   584.28     6.18
11:        3   155.67     4.04
12:        1   137.28     3.65
13:        4   181.87     4.84
14:        5   152.95     4.07
15:        6   150.07     3.99
16:        7   156.41     4.16
17:        8   108.19     2.88
18:        9   162.76     4.33
19:       10   175.88     4.68
20:       11   160.88     4.28
21:        2   148.53     3.95
22:        3   155.28     4.13
23:        1    62.84    10.49
24:        4   145.73    10.85
25:        5    12.00     8.08
26:        6    68.25     8.92
27:        7   143.88    11.83
28:        8     0.12     0.56
29:        9     0.22     1.04
30:       10     0.39     1.80
31:       11   162.22    12.08
32:        2   115.77     8.62
33:        3     0.11     0.51
</code>```

The code I am using is

```<code>ggplot(ngames, aes(x= 'New Name', y= 'Ld P Min')) + geom_bar(stat = "summary")
</code>```

which gives me this incorrect graph

bad graph.

I have been able to create an example graph of what I'm looking for using stock data from iris, but it doesn't seem to work with my data despite all of data formats being identical to those in iris. example of expected graph. The code for this graph is

```<code>ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_bar(stat = "identity")
</code>```

Thanks for the help.

答:
I'm not sure this is everything, because there is no reproducible example, but what I see right away is:

1) ggplot does not need to have variable names in quotes. If you have variable names with spaces in them, use tick marks instead. Also, it's better if you specify which parameters you are defining. So change your first line to

```<code>ggplot(games, aes(x=`Player Name`, y=`Player Load Per Minute`));
</code>```

2) As mentioned in the comments above, your geom_bar statement is using parameters that don't need to be there. The error you are getting literally says "ggplot does not know what stat = "summary" or fun.y = 'mean' means." I would suggest, instead of using YouTube videos as your guide, use the GGplot Reference.

Body:
Very new to R programming and trying to create a bar plot, however my categorical x variable remains grouped together and I get a single bar without any usable information. A subsample is as follows:

     New Name Tot Pl L Ld P Min
 1:        1   376.62     5.91
 2:        4   689.07     7.26
 3:        5   202.14     4.67
 4:        6   516.28     6.01
 5:        7   698.02     7.41
 6:        8   180.50     3.69
 7:        9   163.12     4.24
 8:       10   176.66     4.59
 9:       11   665.34     7.97
10:        2   584.28     6.18
11:        3   155.67     4.04
12:        1   137.28     3.65
13:        4   181.87     4.84
14:        5   152.95     4.07
15:        6   150.07     3.99
16:        7   156.41     4.16
17:        8   108.19     2.88
18:        9   162.76     4.33
19:       10   175.88     4.68
20:       11   160.88     4.28
21:        2   148.53     3.95
22:        3   155.28     4.13
23:        1    62.84    10.49
24:        4   145.73    10.85
25:        5    12.00     8.08
26:        6    68.25     8.92
27:        7   143.88    11.83
28:        8     0.12     0.56
29:        9     0.22     1.04
30:       10     0.39     1.80
31:       11   162.22    12.08
32:        2   115.77     8.62
33:        3     0.11     0.51

The code I am using is

ggplot(ngames, aes(x= 'New Name', y= 'Ld P Min')) + geom_bar(stat = "summary")

which gives me this incorrect graph

bad graph.

I have been able to create an example graph of what I'm looking for using stock data from iris, but it doesn't seem to work with my data despite all of data formats being identical to those in iris. example of expected graph. The code for this graph is

ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_bar(stat = "identity")

Thanks for the help.

Body:
I'm not sure this is everything, because there is no reproducible example, but what I see right away is:

1) ggplot does not need to have variable names in quotes. If you have variable names with spaces in them, use tick marks instead. Also, it's better if you specify which parameters you are defining. So change your first line to

ggplot(games, aes(x=`Player Name`, y=`Player Load Per Minute`));

2) As mentioned in the comments above, your geom_bar statement is using parameters that don't need to be there. The error you are getting literally says "ggplot does not know what stat = "summary" or fun.y = 'mean' means." I would suggest, instead of using YouTube videos as your guide, use the GGplot Reference.


问:
Sorting v-data-table checks checkboxes
Is anyone able to determine why sorting this table will automatically check some boxes? And how the boxes can be checked when their value is not in the "checked" array?

    <v-app id="inspire">

            <v-data-table
                show-select
                :headers="headers"
                :items="desserts"
                class="elevation-1"
            >
                <template v-slot:items="props">
                    <v-checkbox v-model="checked" :value="props.item.name" />
                    {{ props.item.name }}
                    {{ props.item.calories }}
                </template>
            </v-data-table>

    </v-app>

```

CodePen: https://codepen.io/EoghanCurtin/pen/ExPYqpY

答:
The weirdness is related to a few overlapping invalid values:

you're using the same v-model for all checkboxes

you're using a string instead of boolean as v-model for checkboxes. It's actually an array of strings before you sort for the first time and then it becomes string (because of :value attribute on <v-checkbox>, pointing at a string).

Test with ```{{checked}}``` in your codepen.

you're closing the first  twice (invalid html).

A possible fix:

```<code><template v-slot:items="{ item }">
  <td><v-checkbox v-model="cb[item.name]" /></td>
  <td v-text="item.name" />
  <td class="text-xs-right" v-text="item.calories" />
</template>
</code>```

...

```<code>data: () => ({
  cb: {},
  ...
}),
computed: {
  checked() {
    return Object.entries(this.cb)
      .filter(o => o[1]).map(o => o[0])
    }
},
...
</code>```

See it working here.

Title: Sorting v-data-table checks checkboxes

Body:
Is anyone able to determine why sorting this table will automatically check some boxes? And how the boxes can be checked when their value is not in the "checked" array?

    <v-app id="inspire">

            <v-data-table
                show-select
                :headers="headers"
                :items="desserts"
                class="elevation-1"
            >
                <template v-slot:items="props">
                    <v-checkbox v-model="checked" :value="props.item.name" />
                    {{ props.item.name }}
                    {{ props.item.calories }}
                </template>
            </v-data-table>

    </v-app>

CodePen: https://codepen.io/EoghanCurtin/pen/ExPYqpY

Body:
The weirdness is related to a few overlapping invalid values:

you're using the same v-model for all checkboxes

you're using a string instead of boolean as v-model for checkboxes. It's actually an array of strings before you sort for the first time and then it becomes string (because of :value attribute on <v-checkbox>, pointing at a string).

Test with <pre>{{checked}}</pre> in your codepen.

you're closing the first <td> twice (invalid html).

A possible fix:

<template v-slot:items="{ item }">
  <td><v-checkbox v-model="cb[item.name]" /></td>
  <td v-text="item.name" />
  <td class="text-xs-right" v-text="item.calories" />
</template>

...

data: () => ({
  cb: {},
  ...
}),
computed: {
  checked() {
    return Object.entries(this.cb)
      .filter(o => o[1]).map(o => o[0])
    }
},
...

See it working here.


问:
Can't access keys in the dict
```<code>books = ['book1', 'book2', 'book3']
names = ['anas', 'jana', 'mo']
biglist = [{'anas' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'jana' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'mo' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]
</code>```

I was planning to calculate the average for each book(excluding the zeros), so i came up with this list comprehension:

```<code>ratings={book:[biglist[i][names[j]][book] for i, _ in enumerate(biglist)] for book in books for j in range(len(names))}
sum_of_ratings = {book:sum(ratings[book]) for book in books}
avg_of_ratings =  {book:sum_of_ratings[book]/len(ratings[book]) for book in books}
</code>```

But when i run the code it gives this output:

```<code>ratings={book:[biglist[i][names[j]][book] for i, _ in enumerate(biglist)] for book in books for j in range(len(names))}
KeyError: 'anas'
</code>```

Apparently, it doesn't find the keys even though is the same as the ones in the list.

NOTE : i'm not going to be using any built in functions in order to
   compute the average.

答:
Your comprehension uses three different methods to iterate over a list; just use the simplest one!

You also forgot to exclude the zeroes from the average calculation (you'd need to take the len of the list minus the zero elements).  It's simpler to just use statistics.mean and filter the zeroes out first.

You also don't even need the "user" keys since they aren't a part of this calculation, so doing lookups based on those adds more unnecessary complexity.  Just take the values of those dicts:

```<code>>>> ratings = {book: [d[book] for u in biglist for d in u.values()] for book in books}
>>> ratings
{'book1': [0, 5, 1], 'book2': [-2, 0, 5], 'book3': [3, -3, 3]}
>>> from statistics import mean
>>> avg_ratings = {book: mean(r for r in ratings[book] if r != 0) for book in books}
>>> avg_ratings
{'book1': 3, 'book2': 1.5, 'book3': 1}
</code>```

Or you could just condense the whole thing into a single comprehension:

```<code>avg_ratings = {book: mean(
    d[book] for u in biglist for d in u.values() if d[book] != 0
) for book in books}
</code>```

Title: Can't access keys in the dict

Body:
books = ['book1', 'book2', 'book3']
names = ['anas', 'jana', 'mo']
biglist = [{'anas' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'jana' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'mo' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]

I was planning to calculate the average for each book(excluding the zeros), so i came up with this list comprehension:

ratings={book:[biglist[i][names[j]][book] for i, _ in enumerate(biglist)] for book in books for j in range(len(names))}
sum_of_ratings = {book:sum(ratings[book]) for book in books}
avg_of_ratings =  {book:sum_of_ratings[book]/len(ratings[book]) for book in books}

But when i run the code it gives this output:

ratings={book:[biglist[i][names[j]][book] for i, _ in enumerate(biglist)] for book in books for j in range(len(names))}
KeyError: 'anas'

Apparently, it doesn't find the keys even though is the same as the ones in the list.

NOTE : i'm not going to be using any built in functions in order to
   compute the average.

Body:
Your comprehension uses three different methods to iterate over a list; just use the simplest one!

You also forgot to exclude the zeroes from the average calculation (you'd need to take the len of the list minus the zero elements).  It's simpler to just use statistics.mean and filter the zeroes out first.

You also don't even need the "user" keys since they aren't a part of this calculation, so doing lookups based on those adds more unnecessary complexity.  Just take the values of those dicts:

>>> ratings = {book: [d[book] for u in biglist for d in u.values()] for book in books}
>>> ratings
{'book1': [0, 5, 1], 'book2': [-2, 0, 5], 'book3': [3, -3, 3]}
>>> from statistics import mean
>>> avg_ratings = {book: mean(r for r in ratings[book] if r != 0) for book in books}
>>> avg_ratings
{'book1': 3, 'book2': 1.5, 'book3': 1}

Or you could just condense the whole thing into a single comprehension:

avg_ratings = {book: mean(
    d[book] for u in biglist for d in u.values() if d[book] != 0
) for book in books}


问:
MongoDB auto increment ID
The size of the auto generated ID in MongodDB is 12 Bytes and the size of a big integer is 8 bytes. I have a mongodb cluster on 4 machines running Ubuntu Server, but I am just testing things now. Inserts can be done only through one server which is a nodejs server, but updates and deletes can be done using various machines running a native c application all around the world and the nodejs server.

Since I have full control over inserts, wouldn't it be better to use an auto increment id?

in 1MB of memory you can save 87381 of 12 byte ids and 131027 of the 8
byte ids.

is it worth it to go for auto increment ids and is there a benefit
other than saving memory?

performance-wise wouldn't comparing a 8 byte id be faster than a 12
byte id, and wouldn't it reduce the size if i do indexing?

How am i doing it :

i have this document

```<code>{id:0 latestId:174845423}
</code>```

i very rarely increment it by 1, most of my inserts are bulk inserts, so the nodejs server modifies the documents to be inserted in a loop giving each one an incremented id, at the end of the insert operation i add i update the lastest id with the last id value.

答:
If you don't have a distributed system then you can use the file system (fs) module of node js and keep track of all the records there. Then you can save that value in mongo dB.

P.S. - This can work if you don't have a distributed system.

Alternatively

You can make a queue of records for the incoming data entries and then save it in dB.

Title: MongoDB auto increment ID

Body:
The size of the auto generated ID in MongodDB is 12 Bytes and the size of a big integer is 8 bytes. I have a mongodb cluster on 4 machines running Ubuntu Server, but I am just testing things now. Inserts can be done only through one server which is a nodejs server, but updates and deletes can be done using various machines running a native c application all around the world and the nodejs server.

Since I have full control over inserts, wouldn't it be better to use an auto increment id?

in 1MB of memory you can save 87381 of 12 byte ids and 131027 of the 8
byte ids.

is it worth it to go for auto increment ids and is there a benefit
other than saving memory?

performance-wise wouldn't comparing a 8 byte id be faster than a 12
byte id, and wouldn't it reduce the size if i do indexing?

How am i doing it :

i have this document

{id:0 latestId:174845423}

i very rarely increment it by 1, most of my inserts are bulk inserts, so the nodejs server modifies the documents to be inserted in a loop giving each one an incremented id, at the end of the insert operation i add i update the lastest id with the last id value.


问:
Create dataframe of correlation and p values using group_by then plot with error bars in R
I want to plot the correlation between several factors in my data set. If possible, I'd like to try to add error bars or whiskers to these plotted values.
Prior to calculating the values, I first want to group them according to the values in one of the columns. I would like to use a tidyverse solution if possible. I am able to achieve half of this using cor(), but I don't know how to add an additional column that contains the p value.

I think the iris data set demonstrates what I'd like to do fairly well. The actual data uses a time series along the x axis. I have spearman specified because that's the correlation used in my analysis, not because it's the correct choice in the iris data set. I've seen some other posts suggesting the use of cor.test and pulling the values from that, but I'm not sure how that would be applied back to the bar chart to use as error bars. Here's the code to create the basic bar chart below.

Edit I have changed my example from using the mtcars data set to the iris data set as I think it better reflects my data. While the initial answer to the question by jay.sf worked with the mtcars set and was greatly appreciated, it didn't work with my data set and the iris set threw the same errors I was having. Additionally, I hadn't stated this in the original, but a tidyverse solution is preferable, but not necessary.

I think that the answer I'm looking for might be contained here, but I'm still trying to work out the details: https://dominicroye.github.io/en/2019/tidy-correlation-tests-in-r/.

```<code>iristest <- iris %>%
  group_by(Species) %>%
  summarise(COR = cor(Sepal.Length,Sepal.Width, method = "spearman", use="complete.obs"))

ggplot(data = iristest) +
  aes(x = Species, y = COR) +
  geom_bar(stat = "identity") +
  theme_minimal()
</code>```

As it is, iristest provides this output:

```<code>    Species     COR
1   setosa      0.7553375
2   versicolor  0.5176060
3   virginica   0.4265165
</code>```

I think ideally I'd like the output to have the p values added after the COR column.

```<code>    Species     COR          p-value
1   setosa      0.7553375    ###
2   versicolor  0.5176060    ###
3   virginica   0.4265165    ###
</code>```

答:
Here is a version that achieves what is asked for.
Broken down into steps, it is slightly longer than the above examples. This version only uses base R though which may be of interest to some.

```<code># Just extract the columns used in your question
data = iris[, c("Sepal.Length", "Sepal.Width", "Species")]

# Group the data by species
grouped.data = by(data, (data$Species), list)
# Run the function 'cor.test' (from stats) over the data from each species
cor.results = lapply(grouped.data, function(x) cor.test(x$Sepal.Length, x$Sepal.Width, method = "spearman", exact = FALSE) )
# Extract the rho and p-value
rho = sapply(cor.results, "[[", "estimate"))
p = sapply(cor.results, "[[", "p.value")
# Bundle the results into a data.frame (or whatever data structure you prefer)
data.frame(Species = names(cor.results), COR = rho, `p-value` = p, row.names = NULL)
</code>```

```<code>     Species       COR      p.value
1     setosa 0.7553375 2.316710e-10
2 versicolor 0.5176060 1.183863e-04
3  virginica 0.4265165 2.010675e-03
</code>```

[See the note in ?cor.test about the use of exact = FALSE which is necessary for these data.]

Body:
I want to plot the correlation between several factors in my data set. If possible, I'd like to try to add error bars or whiskers to these plotted values.
Prior to calculating the values, I first want to group them according to the values in one of the columns. I would like to use a tidyverse solution if possible. I am able to achieve half of this using cor(), but I don't know how to add an additional column that contains the p value.

I think the iris data set demonstrates what I'd like to do fairly well. The actual data uses a time series along the x axis. I have spearman specified because that's the correlation used in my analysis, not because it's the correct choice in the iris data set. I've seen some other posts suggesting the use of cor.test and pulling the values from that, but I'm not sure how that would be applied back to the bar chart to use as error bars. Here's the code to create the basic bar chart below.

Edit I have changed my example from using the mtcars data set to the iris data set as I think it better reflects my data. While the initial answer to the question by jay.sf worked with the mtcars set and was greatly appreciated, it didn't work with my data set and the iris set threw the same errors I was having. Additionally, I hadn't stated this in the original, but a tidyverse solution is preferable, but not necessary.

I think that the answer I'm looking for might be contained here, but I'm still trying to work out the details: https://dominicroye.github.io/en/2019/tidy-correlation-tests-in-r/.

iristest <- iris %>%
  group_by(Species) %>%
  summarise(COR = cor(Sepal.Length,Sepal.Width, method = "spearman", use="complete.obs"))

ggplot(data = iristest) +
  aes(x = Species, y = COR) +
  geom_bar(stat = "identity") +
  theme_minimal()

As it is, iristest provides this output:

    Species     COR
1   setosa      0.7553375
2   versicolor  0.5176060
3   virginica   0.4265165

I think ideally I'd like the output to have the p values added after the COR column.

    Species     COR          p-value
1   setosa      0.7553375    ###
2   versicolor  0.5176060    ###
3   virginica   0.4265165    ###

Body:
Here is a version that achieves what is asked for.
Broken down into steps, it is slightly longer than the above examples. This version only uses base R though which may be of interest to some.

# Just extract the columns used in your question
data = iris[, c("Sepal.Length", "Sepal.Width", "Species")]

# Group the data by species
grouped.data = by(data, (data$Species), list)
# Run the function 'cor.test' (from stats) over the data from each species
cor.results = lapply(grouped.data, function(x) cor.test(x$Sepal.Length, x$Sepal.Width, method = "spearman", exact = FALSE) )
# Extract the rho and p-value
rho = sapply(cor.results, "[[", "estimate"))
p = sapply(cor.results, "[[", "p.value")
# Bundle the results into a data.frame (or whatever data structure you prefer)
data.frame(Species = names(cor.results), COR = rho, `p-value` = p, row.names = NULL)

     Species       COR      p.value
1     setosa 0.7553375 2.316710e-10
2 versicolor 0.5176060 1.183863e-04
3  virginica 0.4265165 2.010675e-03

[See the note in ?cor.test about the use of exact = FALSE which is necessary for these data.]


问:
configure error: Package requirements (sqlite3 > 3.7.4) were not met
I'm trying to install php on Centos 7 following instructions from: https://www.php.net/manual/en/install.unix.nginx.php.
My nginx version: nginx/1.19.0

I downloaded php-7.4.6.tar.gz from https://www.php.net/downloads
but
at the step:

```<code>./configure --enable-fpm --with-mysqli
</code>```

I got this error:

```<code>checking for sqlite3 > 3.7.4... no
configure: error: Package requirements (sqlite3 > 3.7.4) were not met:

No package 'sqlite3' found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables SQLITE_CFLAGS
and SQLITE_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
</code>```

I do have sqlite3 up and running:

```<code># sqlite3
SQLite version 3.7.17
</code>```

So, how should I set the environment variable (in configure file?)?
Thanks!

答:
To compile from source, dependencies need to be available as a linkable library (and sometimes headers which the new program uses for building). -devel packages install these libraries, so to build PHP from source with SQLite support, you need to install sqlite-devel.

If you have Ubuntu >= 20.04, install this package libsqlite3-dev to satisfy the dev dependency/package requirements.

Body:
I'm trying to install php on Centos 7 following instructions from: https://www.php.net/manual/en/install.unix.nginx.php.
My nginx version: nginx/1.19.0

I downloaded php-7.4.6.tar.gz from https://www.php.net/downloads
but
at the step:

./configure --enable-fpm --with-mysqli

I got this error:

checking for sqlite3 > 3.7.4... no
configure: error: Package requirements (sqlite3 > 3.7.4) were not met:

No package 'sqlite3' found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables SQLITE_CFLAGS
and SQLITE_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.

I do have sqlite3 up and running:

# sqlite3
SQLite version 3.7.17

So, how should I set the environment variable (in configure file?)?
Thanks!


问:
How to access session variables from any class in ASP.NET?
I have created a class file in the App_Code folder in my application. I have a session variable

```<code>Session["loginId"]
</code>```

I want to access this session variables in my class, but when I am writing the following line then it gives error

```<code>Session["loginId"]
</code>```

Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)

答:
Access the Session via the thread's HttpContext:-</p>
```<code>HttpContext.Current.Session["loginId"]
</code>```

OwnerDisplayName: Prashant

Body:
I have created a class file in the App_Code folder in my application. I have a session variable

Session["loginId"]

I want to access this session variables in my class, but when I am writing the following line then it gives error

Session["loginId"]

Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)

LastEditorDisplayName: Martin

Body:
Access the Session via the thread's HttpContext:-

HttpContext.Current.Session["loginId"]

OwnerDisplayName: AnthonyWJones


问:
PL/SQL DB triggers - Make insertion fail if a given condition is not met
I have a small test database I'm using for learning SQL.

There's a Duel table, which contains two Pilot foreign keys (the duelists). I want to check if the duelists haven't already "met" before insertion.

Pseudocode:

```<code>before insertion on Duel
for each row already in the table
  if ((new_row.numpilot1 = old_row.numpilot1 and new_row.numpilot2 = old_row.numpilot2) OR
      (new_row.numpilot1 = old_row.numpilot2 and new_row.numpilot2 = old_row.numpilot1)
     )
    insertion fails
</code>```

One other alternative would be

```<code>tempnum integer;
select numpilot1 into tempnum from duel
where (:NEW.numpilot1 = numpilot1 and :NEW.numpilot2 = numpilot2) OR
      (:NEW.numpilot1 = numpilot2 and :NEW.numpilot2 = numpilot1);

if tempnum == null
    fail insertion
</code>```

What is the PL/SQL (Oracle DBMS) version of this?

答:
You could use a function-based index:

```<code>create unique index duel_uk on duel
( least(numpilot1, numpilot2), greatest(numpilot1, numpilot2));
</code>```

The answer you are clearly seeking is a trigger like this:

```<code>create trigger duel_trg
before insert on duel
for each row
declare
  dummy number;
begin
  select count(*)
  into dummy
  from duel
  where (numpilot1 = :new.numpilot1 and numpilot2 = :new.numpilot2)
  or (numpilot1 = :new.numpilot2 and numpilot2 = :new.numpilot1);

  if dummy > 0 then
    raise_application_error(-20001,'You lose');
  end if;
end;
</code>```

However, that will fail to ensure integrity in a multi-user (or multi-session) environment, as this can happen:

```<code>User1> insert into duel (numpilot1, numpilot2) values (1,2);
-- trigger checks, all seems OK

User2> insert into duel (numpilot1, numpilot2) values (1,2);
-- trigger checks, all seems OK (can't see User1's new row
-- as it hasn't been committed)

User1> commit;
User2> commit;
</code>```

Result: corrupt database.  So while this trigger may satisfy the teacher, it is a bad solution and constraints should be used instead (preferably Justin's solution rather than mine!)

Body:
I have a small test database I'm using for learning SQL.

There's a Duel table, which contains two Pilot foreign keys (the duelists). I want to check if the duelists haven't already "met" before insertion.

Pseudocode:

before insertion on Duel
for each row already in the table
  if ((new_row.numpilot1 = old_row.numpilot1 and new_row.numpilot2 = old_row.numpilot2) OR
      (new_row.numpilot1 = old_row.numpilot2 and new_row.numpilot2 = old_row.numpilot1)
     )
    insertion fails

One other alternative would be

tempnum integer;
select numpilot1 into tempnum from duel
where (:NEW.numpilot1 = numpilot1 and :NEW.numpilot2 = numpilot2) OR
      (:NEW.numpilot1 = numpilot2 and :NEW.numpilot2 = numpilot1);

if tempnum == null
    fail insertion

What is the PL/SQL (Oracle DBMS) version of this?

Body:
You could use a function-based index:

create unique index duel_uk on duel
( least(numpilot1, numpilot2), greatest(numpilot1, numpilot2));

The answer you are clearly seeking is a trigger like this:

create trigger duel_trg
before insert on duel
for each row
declare
  dummy number;
begin
  select count(*)
  into dummy
  from duel
  where (numpilot1 = :new.numpilot1 and numpilot2 = :new.numpilot2)
  or (numpilot1 = :new.numpilot2 and numpilot2 = :new.numpilot1);

  if dummy > 0 then
    raise_application_error(-20001,'You lose');
  end if;
end;

However, that will fail to ensure integrity in a multi-user (or multi-session) environment, as this can happen:

User1> insert into duel (numpilot1, numpilot2) values (1,2);
-- trigger checks, all seems OK

User2> insert into duel (numpilot1, numpilot2) values (1,2);
-- trigger checks, all seems OK (can't see User1's new row
-- as it hasn't been committed)

User1> commit;
User2> commit;

Result: corrupt database.  So while this trigger may satisfy the teacher, it is a bad solution and constraints should be used instead (preferably Justin's solution rather than mine!)


问:
Not able to figure out why Docker build command is not working
I am trying to build a Docker image with given below steps and try to run a docker build command to generate an image in Windows 10 machine. I am not getting any error or so for the steps I am following.
Can someone help me on below and also let me know if any details are required.

```<code>FROM node:10-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD [ "npm","run","start" ]
</code>```

Powershell Screenshot

答:
In your dockerfile you are missing a port to expose which is important to communicate from container to outside of the world.

Add this line in your dockerfile

```<code>EXPOSE 8080
</code>```

PS:

Your dockerfile should look like following. And place your dockerfile in the root directory of your project.

```<code>FROM node:10

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080

CMD [ "npm","run","start" ]
</code>```

Body:
I am trying to build a Docker image with given below steps and try to run a docker build command to generate an image in Windows 10 machine. I am not getting any error or so for the steps I am following.
Can someone help me on below and also let me know if any details are required.

FROM node:10-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD [ "npm","run","start" ]

Powershell Screenshot

Body:
In your dockerfile you are missing a port to expose which is important to communicate from container to outside of the world.

Add this line in your dockerfile

EXPOSE 8080

PS:

Your dockerfile should look like following. And place your dockerfile in the root directory of your project.

FROM node:10

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080

CMD [ "npm","run","start" ]


问:
Kotlin - Check if one map contains all entries from another
I'm trying to create a function in kotlin that takes two maps and returns true if one is contained in another, that is, if all the entries in map A are in map B (but B can have other entries)

The code I have is

```<code>private fun matchesMap(map1: Map<String, Any>, reference: Map<String, Any>): Boolean {
    return reference.all { k, v ->  map1.get(k).equals(v) }
}
</code>```

But this gives a Type mismatch: inferred type is (Map.Entry<String, Any>, ???) -> Boolean but (Map.Entry<String, Any>) -> Boolean was expected and I'm not sure what's wrong. I've tried to replace it with map1[k] == v but I still get the same error. How can I fix the compilation error?

答:
The reason why it doesn't compile is that you forgot a pair of parenthesis around k, v. This makes a big difference because with the parenthesis you're creating a lambda expecting 1 argument, which is destructured into 2 variables (k and v), while without parenthesis you're providing a lambda that expects 2 different arguments. The latter is incompatible with the signature of all, as correctly pointed out by @Gennady.

Also, another problem is caused by the .equals method, because get is returning a nullable value (what if there's no such key in the map?), so the equals method should be invoked as ?.equals, which can be simplified to ==. Also, get can be simplified too to [].

Putting all together:

```<code>private fun matchesMap(map1: Map<String, Any>, reference: Map<String, Any>): Boolean {
    return reference.all { (k, v) ->  map1[k] == v }
}
</code>```

Body:
I'm trying to create a function in kotlin that takes two maps and returns true if one is contained in another, that is, if all the entries in map A are in map B (but B can have other entries)

The code I have is

private fun matchesMap(map1: Map<String, Any>, reference: Map<String, Any>): Boolean {
    return reference.all { k, v ->  map1.get(k).equals(v) }
}

But this gives a Type mismatch: inferred type is (Map.Entry<String, Any>, ???) -> Boolean but (Map.Entry<String, Any>) -> Boolean was expected and I'm not sure what's wrong. I've tried to replace it with map1[k] == v but I still get the same error. How can I fix the compilation error?

Body:
The reason why it doesn't compile is that you forgot a pair of parenthesis around k, v. This makes a big difference because with the parenthesis you're creating a lambda expecting 1 argument, which is destructured into 2 variables (k and v), while without parenthesis you're providing a lambda that expects 2 different arguments. The latter is incompatible with the signature of all, as correctly pointed out by @Gennady.

Also, another problem is caused by the .equals method, because get is returning a nullable value (what if there's no such key in the map?), so the equals method should be invoked as ?.equals, which can be simplified to ==. Also, get can be simplified too to [].

Putting all together:

private fun matchesMap(map1: Map<String, Any>, reference: Map<String, Any>): Boolean {
    return reference.all { (k, v) ->  map1[k] == v }
}


问:
Link between HTML and CSS not functioning

body {
  background-color: grey;
}

hr {
  border-style: none;
  border-top-style: dotted;
  border-color: #12947f;
  border-width: 4px;
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Donald's Personal Site</title>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
</body>
</html></code>```

I am new to coding and I've spent three days trying to figure out what was wrong with my page. Could someone please help me to resolve this issue, so that I can continue to improve on my coding?

答:
Your code misses some HTML tags
You never declared body, hr tags in your HTML doc file and trying to modify them in CSS sheet. It doesn't make any sense.
Here I fixed your mistakes, Have a look

```<code>    <!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Donald's Personal Site</title>
            <link rel="stylesheet" href="css/style.css">
        </head>

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

Also, make sure href to CSS file is right.

Body:
body {
  background-color: grey;
}

hr {
  border-style: none;
  border-top-style: dotted;
  border-color: #12947f;
  border-width: 4px;
  width: 50%;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Donald's Personal Site</title>
  <link rel="stylesheet" href="css/style.css">

I am new to coding and I've spent three days trying to figure out what was wrong with my page. Could someone please help me to resolve this issue, so that I can continue to improve on my coding?

Body:
Your code misses some HTML tags
You never declared body, hr tags in your HTML doc file and trying to modify them in CSS sheet. It doesn't make any sense.
Here I fixed your mistakes, Have a look

    <!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Donald's Personal Site</title>
            <link rel="stylesheet" href="css/style.css">
        </head>

       <body>
           <hr>
       </body>
   </html>

Also, make sure href to CSS file is right.


问:
Printing long value to hex with leading zeroes
I've been using this function to print int values with leading zeroes with 4 decimals, which has been working well.

Use Arduino IDE 1.8.12

```<code>void printHex(int num, int precision)
{
  Serial.println(num);
  char tmp[16];
  char format[128];
  sprintf(format, "%%.%dX", precision);
  sprintf(tmp, format, num);
  Serial.println(tmp);
}
</code>```

Calling the function printHex(100,4) prints out 0064

I now want to print long values with 5 decimals but its not as simple as I thought.

Eg printHex(200000,5) should print out 30D40, and printHex(0,5) should print 00000

I tried changing int num to long num and its printing 5 digits, but the MSB is always 0

Currently I'm getting 00D40 instead of 30D40

答:
Figured it out, had to use uint32_t and long in the sprintf</p>

```<code>void printHex(uint32_t num, int precision)
{
  char tmp[16];
  char format[128];
  sprintf(format, "%%0%dlX", precision);
  sprintf(tmp, format, num);
  Serial.print(tmp);

}
</code>```

Body:
I've been using this function to print int values with leading zeroes with 4 decimals, which has been working well.

Use Arduino IDE 1.8.12

void printHex(int num, int precision)
{
  Serial.println(num);
  char tmp[16];
  char format[128];
  sprintf(format, "%%.%dX", precision);
  sprintf(tmp, format, num);
  Serial.println(tmp);
}

Calling the function printHex(100,4) prints out 0064

I now want to print long values with 5 decimals but its not as simple as I thought.

Eg printHex(200000,5) should print out 30D40, and printHex(0,5) should print 00000

I tried changing int num to long num and its printing 5 digits, but the MSB is always 0

Currently I'm getting 00D40 instead of 30D40

Body:
Figured it out, had to use uint32_t and long in the sprintf

void printHex(uint32_t num, int precision)
{
  char tmp[16];
  char format[128];
  sprintf(format, "%%0%dlX", precision);
  sprintf(tmp, format, num);
  Serial.print(tmp);

}


问:
Quartus does not allow using a Generate block in Verilog
Pretty simple problem. Given the following code:

```<code>module main(
    output reg  [1:0][DATA_WIDTH-1:0] dOut,
    input  wire [1:0][DATA_WIDTH-1:0] dIn,
    input  wire [1:0][ADDR_WIDTH-1:0] addr,
    input  wire [1:0] wren,
    input  wire clk
);
    parameter DATA_WIDTH = 16;
    parameter ADDR_WIDTH = 6;

    reg [DATA_WIDTH-1:0] ram [2**ADDR_WIDTH-1:0];

    generate
        genvar k;
        for(k=0; k<2; k=k+1) begin: m
            always @(posedge clk) begin
                if(wren[k])
                    ram[addr[k]] <= dIn[k];
                dOut[k] <= ram[addr[k]];
            end
        end
    endgenerate
endmodule
</code>```

quarus 13.0sp1 gives this error (and its 20 other ill-begotten fraternally equivalent siblings):

Error (10028): Can't resolve multiple constant drivers for net "ram[63][14]" at main.v(42)

But if I manually un-roll the generate loop:

```<code>module main(
    output reg  [1:0][DATA_WIDTH-1:0] dOut,
    input  wire [1:0][DATA_WIDTH-1:0] dIn,
    input  wire [1:0][ADDR_WIDTH-1:0] addr,
    input  wire [1:0] wren,
    input  wire clk
);
    parameter DATA_WIDTH = 16;
    parameter ADDR_WIDTH = 6;

    reg [DATA_WIDTH-1:0] ram [2**ADDR_WIDTH-1:0];

    always @(posedge clk) begin
        if(wren[0])
            ram[addr[0]] <= dIn[0];
        dOut[0] <= ram[addr[0]];
    end

    always @(posedge clk) begin
        if(wren[1])
            ram[addr[1]] <= dIn[1];
        dOut[1] <= ram[addr[1]];
    end
endmodule
</code>```

It all becomes okay with the analysis & synthesis step.

What's the cure to get the generate loop running?

答:
I think the correct way is in the lines of what it's explained in this question: Using a generate with for loop in verilog

Which would be transferred to your code as this:

```<code>module main(
    output reg  [1:0][DATA_WIDTH-1:0] dOut,
    input  wire [1:0][DATA_WIDTH-1:0] dIn,
    input  wire [1:0][ADDR_WIDTH-1:0] addr,
    input  wire [1:0] wren,
    input  wire clk
);
    parameter DATA_WIDTH = 16;
    parameter ADDR_WIDTH = 6;

    reg [DATA_WIDTH-1:0] ram [2**ADDR_WIDTH-1:0];
    integer k;

    always @(posedge clk) begin
      for(k=0; k<2; k=k+1) begin:
        if(wren[k])
          ram[addr[k]] <= dIn[k];
        dOut[k] <= ram[addr[k]];
      end
    end
endmodule
</code>```

Keeping all accesses to your dual port RAM in one always block is convenient so the synthesizer can safely detect that you are efefctively using a dual port RAM at register ram.

Body:
Pretty simple problem. Given the following code:

module main(
    output reg  [1:0][DATA_WIDTH-1:0] dOut,
    input  wire [1:0][DATA_WIDTH-1:0] dIn,
    input  wire [1:0][ADDR_WIDTH-1:0] addr,
    input  wire [1:0] wren,
    input  wire clk
);
    parameter DATA_WIDTH = 16;
    parameter ADDR_WIDTH = 6;

    reg [DATA_WIDTH-1:0] ram [2**ADDR_WIDTH-1:0];

    generate
        genvar k;
        for(k=0; k<2; k=k+1) begin: m
            always @(posedge clk) begin
                if(wren[k])
                    ram[addr[k]] <= dIn[k];
                dOut[k] <= ram[addr[k]];
            end
        end
    endgenerate
endmodule

quarus 13.0sp1 gives this error (and its 20 other ill-begotten fraternally equivalent siblings):

Error (10028): Can't resolve multiple constant drivers for net "ram[63][14]" at main.v(42)

But if I manually un-roll the generate loop:

module main(
    output reg  [1:0][DATA_WIDTH-1:0] dOut,
    input  wire [1:0][DATA_WIDTH-1:0] dIn,
    input  wire [1:0][ADDR_WIDTH-1:0] addr,
    input  wire [1:0] wren,
    input  wire clk
);
    parameter DATA_WIDTH = 16;
    parameter ADDR_WIDTH = 6;

    reg [DATA_WIDTH-1:0] ram [2**ADDR_WIDTH-1:0];

    always @(posedge clk) begin
        if(wren[0])
            ram[addr[0]] <= dIn[0];
        dOut[0] <= ram[addr[0]];
    end

    always @(posedge clk) begin
        if(wren[1])
            ram[addr[1]] <= dIn[1];
        dOut[1] <= ram[addr[1]];
    end
endmodule

It all becomes okay with the analysis & synthesis step.

What's the cure to get the generate loop running?

Body:
I think the correct way is in the lines of what it's explained in this question: Using a generate with for loop in verilog

Which would be transferred to your code as this:

module main(
    output reg  [1:0][DATA_WIDTH-1:0] dOut,
    input  wire [1:0][DATA_WIDTH-1:0] dIn,
    input  wire [1:0][ADDR_WIDTH-1:0] addr,
    input  wire [1:0] wren,
    input  wire clk
);
    parameter DATA_WIDTH = 16;
    parameter ADDR_WIDTH = 6;

    reg [DATA_WIDTH-1:0] ram [2**ADDR_WIDTH-1:0];
    integer k;

    always @(posedge clk) begin
      for(k=0; k<2; k=k+1) begin:
        if(wren[k])
          ram[addr[k]] <= dIn[k];
        dOut[k] <= ram[addr[k]];
      end
    end
endmodule

Keeping all accesses to your dual port RAM in one always block is convenient so the synthesizer can safely detect that you are efefctively using a dual port RAM at register ram.


问:
Updating width on progress bar when checkbox checked/unchecked

What I'm trying to do

Increase or decrease the progress bar by a value percentage everytime a checkbox in the list is checked or unchecked.

For instance, if there are two checkboxes in the list, then the bar should increase or decrease by 50% when a checkbox is checked/unchecked. If there are 4 checkboxes, then 25% etc etc.

What's working

I can set the percentage that the bar needs to increase/decrease by ok. And I can get the progress to change width to e.g. 50% on first check of a checkbox.

What's not working:

I can't figure out how to increase/decrease the progress by the checklistProgressInterval percentage amount each time. For instance, if the value is 50%, then the progress should increase by 50% each time a checkbox is checked and decrease by 50% when unchecked.

I can get it to increase to 50% but not by 50%. The += just seems to increase it by 1% after each check.

Could anyone help me out with what I'm doing wrong? Thanks

```<code>let checklistItems = document.querySelectorAll('.list--checklist__item'),
    checklistProgressBar = document.querySelector('.progress-bar--checklist .progress-indicator'),
    checklistLen = checklistItems.length,
    checklistProgressInterval = 100 / checklistLen;

checklistItems.forEach((checklistItem) => {
    let checklistInput = checklistItem.querySelector('.input--checklist__input'),
        checklistContainer = checklistItem.querySelector('.input--checklist__container'),
        checklistText = checklistItem.querySelector('.list--checklist__item--text');
    checklistContainer.addEventListener('click', () => {
        if (checklistInput.checked == true) {
            checklistItem.classList.add('finished');
            checklistProgressBar.style.width += `${checklistProgressInterval}%`;
        } else {
            checklistItem.classList.remove('finished');
            checklistProgressBar.style.width -= `${checklistProgressInterval}%`;
        }
    })
});
</code>```

答:
My guess is that you are doing += wrong

Afaik, you can't add width to the style, since you are using a string.
You need to calculate it beforehand and assign a variable.

Also make sure your progress bar parent has a width, like 100px.

Check this example:

So instead of 0% and 50% add a variable here and calculate the % before you assign it.

function checkMe() {
  const checkBoxes = document.querySelectorAll(".myCheckBox");
  const progress = document.querySelector(".progress-inner");
  const checklistProgressInterval = 100 / checkBoxes.length;
  let width = 0;

  for(let i = 0; i < checkBoxes.length; i++){
    if(checkBoxes[i].checked){
      width += checklistProgressInterval;
    }
  }

    progress.style.width = `${width}%`;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.progress{
  width: 150px;
  height: 20px;
  background-color: #333;
  border: 1px solid black;
  }

.progress-inner{
  background-color: #f7f;
  width: 0%;
  height: 100%;
  }</code>```

<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />```

Body:
What I'm trying to do

Increase or decrease the progress bar by a value percentage everytime a checkbox in the list is checked or unchecked.

For instance, if there are two checkboxes in the list, then the bar should increase or decrease by 50% when a checkbox is checked/unchecked. If there are 4 checkboxes, then 25% etc etc.

What's working

I can set the percentage that the bar needs to increase/decrease by ok. And I can get the progress to change width to e.g. 50% on first check of a checkbox.

What's not working:

I can't figure out how to increase/decrease the progress by the checklistProgressInterval percentage amount each time. For instance, if the value is 50%, then the progress should increase by 50% each time a checkbox is checked and decrease by 50% when unchecked.

I can get it to increase to 50% but not by 50%. The += just seems to increase it by 1% after each check.

Could anyone help me out with what I'm doing wrong? Thanks

let checklistItems = document.querySelectorAll('.list--checklist__item'),
    checklistProgressBar = document.querySelector('.progress-bar--checklist .progress-indicator'),
    checklistLen = checklistItems.length,
    checklistProgressInterval = 100 / checklistLen;

checklistItems.forEach((checklistItem) => {
    let checklistInput = checklistItem.querySelector('.input--checklist__input'),
        checklistContainer = checklistItem.querySelector('.input--checklist__container'),
        checklistText = checklistItem.querySelector('.list--checklist__item--text');
    checklistContainer.addEventListener('click', () => {
        if (checklistInput.checked == true) {
            checklistItem.classList.add('finished');
            checklistProgressBar.style.width += `${checklistProgressInterval}%`;
        } else {
            checklistItem.classList.remove('finished');
            checklistProgressBar.style.width -= `${checklistProgressInterval}%`;
        }
    })
});

Body:
My guess is that you are doing += wrong

Afaik, you can't add width to the style, since you are using a string.
You need to calculate it beforehand and assign a variable.

Also make sure your progress bar parent has a width, like 100px.

Check this example:

So instead of 0% and 50% add a variable here and calculate the % before you assign it.

function checkMe() {
  const checkBoxes = document.querySelectorAll(".myCheckBox");
  const progress = document.querySelector(".progress-inner");
  const checklistProgressInterval = 100 / checkBoxes.length;
  let width = 0;

  for(let i = 0; i < checkBoxes.length; i++){
    if(checkBoxes[i].checked){
      width += checklistProgressInterval;
    }
  }

    progress.style.width = `${width}%`;
}

.progress{
  width: 150px;
  height: 20px;
  background-color: #333;
  border: 1px solid black;
  }

.progress-inner{
  background-color: #f7f;
  width: 0%;
  height: 100%;
  }

<div class="progress">
  <div class="progress-inner"></div>
</div>

<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />
<input class="myCheckBox" type="checkbox" onclick="checkMe()" />


问:
In Azure Devops, how can i use pipeline variables in a "Azure CLI task v.2" running shell script?
I am trying to execute a task using Azure CLI and bash in Azure Devops. I am using Azure CLI task v.2 and choosing shell as script type as below.

I want to use pipeline variables in bash script. I run the command below inside the script:

```<code>#!/bin/bash
az role assignment create --role "Lab Admin" --assignee $(ownerEmail) -g $(rgName)
</code>```

and i got the error below:

```<code> line 2: ownerEmail: command not found
 line 2: rgName: command not found
</code>```

I don't understand. Normally, i should be able to use azure cli in a bash script.
Does anybody have an idea?

答:
Variables are passed in as environment variables. The variables are all uppercased and case-sensitive on linux.

Thus, $OWNERNAME and $RGNAME are likely the values you're after.

See the section on variable usage in scripts:

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#environment-variables

There are some tasks that don't populate the environment at all, these have an environment section where you can manually pass in the environment variables.

Body:
I am trying to execute a task using Azure CLI and bash in Azure Devops. I am using Azure CLI task v.2 and choosing shell as script type as below.

I want to use pipeline variables in bash script. I run the command below inside the script:

#!/bin/bash
az role assignment create --role "Lab Admin" --assignee $(ownerEmail) -g $(rgName)

and i got the error below:

 line 2: ownerEmail: command not found
 line 2: rgName: command not found

I don't understand. Normally, i should be able to use azure cli in a bash script.
Does anybody have an idea?


问:
iMacros, selecting one link from a table
I need to make an iMacros script that selects a link with a common caption, based on a value that precedes it in a table. For example, I have a webpage with rows of data that looks like this:

APPLE     Click Me

BANANA    Click Me

PEAR      Click Me

GRAPES    Click Me

ORANGE    Click Me

The "fruit name" is not a hyperlink, but the "Click Me" is.  I want to have my script always click on the link beside "PEAR".

I cannot just use TAG POS=3 because the table is different every time, and PEAR is not always in position 3.

So I need some sort of script that finds the value I specify ("PEAR" in this case), then uses TAG POS=x.

How can I do that?  (prefer to use JS please as I am using the FireFox plugin)

答:
My table was exactly the same, here is what worked for me:</p>

```<code>TAG POS=1 TYPE=TD ATTR=TXT:PEAR
TAG POS=R1 TYPE=A ATTR=txt:*
</code>```

Body:
My table was exactly the same, here is what worked for me:

TAG POS=1 TYPE=TD ATTR=TXT:PEAR
TAG POS=R1 TYPE=A ATTR=txt:*


问:
Difference between a service and a method?
I know a service is a self contained functionality ,now if anyone creates a service following the rest principles then it can be called as a rest service. Now my question is ,if I create a Asp.Net web API project with a controller and several actions like getEmployee(), getEmployeeAddress(int id) actions and so on. then the client will consume it with a url say http://www.aaa.com/employee , then can i say the Action method getEmployee is a service and getEmployeeAddress which is consumed with the url http://www.aaa.com/employee/1 is another service.
or should i say i am offering a single employee management service which has multiple functionalities???</p>

答:
A single webservice EmployeeService with multiple action methods configured with different url's. Services can be created based on the module, since getEmployee and getEmployeeAddress are related to employees, they can be added as action methods within EmployeeService. Also, I am not sure about the plan to have employee address as different endpoint instead of a list object within Employee object. Nevertheless, you can have multiple GET actions within a service.

Read all the employees

Url: /employee

Operation: GET

Read a single employee

Url: /employee/{id}

Operation: GET

Read a employee address(es)

Url: /employee/{id}/address

Operation: GET

For multiple GET operations (obviously with different method names other than default such as 1. GET), make sure you have different url's assigned in the [Route("url")] or [HttpGet("url")] attributes of the action methods.

Additional points, pass the additional information not directly related to the operation such as using paging or sorting in the resultset, via query strings in the url's such as /employee?page=1


问:
How do I find highest value using pointer?
I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.

```<code>#include <iostream>
#include <string>
using namespace std;
int main() {
  int a[10], i, index;
  int *p, *max;
  for (i = 0; i < 10; i++) cin >> a[i];
  max = 0;
  p = &a[10];
  for (index = 0; index < 10; index++) {
    if ((p[index]) > *max) {
      *max = (p[index]);
    }
  }
  cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
  return 0;
}
</code>```

答:
The solution to this problem is recognizing that max should always point to the maximum item seen in the array a so far so instead of initializing max to 0 you start by initializing it to point to the first item in a which is &a[0] or just a.

I tried to make the least amount of changes to the original code:

```<code>#include <iostream>
#include<string>
using namespace std;
int main()
{
    int a[10],i,index;
    int *p,*max;
    for(i=0;i<10;i++)
        cin>>a[i];
    max=a; // Initialize max to point to the first item in a
    p=a;
    for(index=0;index<10;index++){
        if((p[index])>*max){
            max=(&p[index]); // Now make max point to the new maximum item
        }
    }
    cout<<"Highest value="<<*max<<endl<<"is at index="<<max - p<<endl;
    return 0;
}
</code>```

Here is the code in ideone:
https://ideone.com/BwE45C

As mentioned in the comments below p probably is not being used as the question expects so I have rewritten the code to iterate using p

```<code>#include <iostream>
#include<string>
using namespace std;
int main()
{
    int a[10],i,index;
    int *max;
    for(i=0;i<10;i++)
        cin>>a[i];
    max=a;

    for(int* p=a;p<a+10;p++){ // p is now a pointer that is used to iterate through the array
        if(*p>*max){
            max=p; // max points to the new maximum
        }
    }
    cout<<"Highest value="<<*max<<endl<<"is at index="<<max - a<<endl;
    return 0;
}
</code>```

The new ideone link for this is here: https://ideone.com/bk3zoS

Body:
I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.

#include <iostream>
#include <string>
using namespace std;
int main() {
  int a[10], i, index;
  int *p, *max;
  for (i = 0; i < 10; i++) cin >> a[i];
  max = 0;
  p = &a[10];
  for (index = 0; index < 10; index++) {
    if ((p[index]) > *max) {
      *max = (p[index]);
    }
  }
  cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
  return 0;
}

Body:
The solution to this problem is recognizing that max should always point to the maximum item seen in the array a so far so instead of initializing max to 0 you start by initializing it to point to the first item in a which is &a[0] or just a.

I tried to make the least amount of changes to the original code:

#include <iostream>
#include<string>
using namespace std;
int main()
{
    int a[10],i,index;
    int *p,*max;
    for(i=0;i<10;i++)
        cin>>a[i];
    max=a; // Initialize max to point to the first item in a
    p=a;
    for(index=0;index<10;index++){
        if((p[index])>*max){
            max=(&p[index]); // Now make max point to the new maximum item
        }
    }
    cout<<"Highest value="<<*max<<endl<<"is at index="<<max - p<<endl;
    return 0;
}

Here is the code in ideone:
https://ideone.com/BwE45C

As mentioned in the comments below p probably is not being used as the question expects so I have rewritten the code to iterate using p

#include <iostream>
#include<string>
using namespace std;
int main()
{
    int a[10],i,index;
    int *max;
    for(i=0;i<10;i++)
        cin>>a[i];
    max=a;

    for(int* p=a;p<a+10;p++){ // p is now a pointer that is used to iterate through the array
        if(*p>*max){
            max=p; // max points to the new maximum
        }
    }
    cout<<"Highest value="<<*max<<endl<<"is at index="<<max - a<<endl;
    return 0;
}

The new ideone link for this is here: https://ideone.com/bk3zoS


问:
from.is_valid() returns false
I want to save customer entry in my database.
I have created a model form and trying to save it. but its not working.
Where is the problem for this ?

my models.py

```<code>class Customer(models.Model):
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name
</code>```

my forms.py

```<code>class CustomerEntryForm(ModelForm):

    class Meta:
        model = Customer
        fields = ['name', 'phone', 'email']
</code>```

my views.py

```<code>def customer_entry(request):
    if request.method == 'POST':
        form = CustomerEntryForm(request.POST)
        print(form.is_valid())
    context = {'form': form}
    return render(request, 'accounts/entry.html', context)
</code>```

my urls.py

```<code>urlpatterns = [
    path('', views.customer_entry, name="entry"),
    path('register/', views.registerPage, name="register"),
    path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),
    path('home/', views.home, name="home"),
]
</code>```

my template

```<code>    <form method="POST" action="{% url 'entry' %}">
    {% csrf_token %}
    <label for="">Name</label><br>
    <div class="input-group mb-3">
    <input type="text" name="name" class="form-control">
    </div>

    <label for="">Phone</label><br>
    <div class="input-group mb-2">
    <input type="text" name="phone" class="form-control" >
    </div>

    <label for="">Email</label><br>
    <div class="input-group mb-2">
    <input type="text" name="phone" class="form-control" >
    </div>

    <input class="btn login_btn" type="submit" value="save">

</form>
</code>```

答:
You are not sending email field nor its value to your form

```<code>   <label for="">Email</label><br>
    <div class="input-group mb-2">
    <input type="text" name="phone" class="form-control" >
    </div>
</code>```

as you can see name="phone" should be name="email" instead

Title: from.is_valid() returns false

Body:
I want to save customer entry in my database.
I have created a model form and trying to save it. but its not working.
Where is the problem for this ?

my models.py

class Customer(models.Model):
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name

my forms.py

class CustomerEntryForm(ModelForm):

    class Meta:
        model = Customer
        fields = ['name', 'phone', 'email']

my views.py

def customer_entry(request):
    if request.method == 'POST':
        form = CustomerEntryForm(request.POST)
        print(form.is_valid())
    context = {'form': form}
    return render(request, 'accounts/entry.html', context)

my urls.py

urlpatterns = [
    path('', views.customer_entry, name="entry"),
    path('register/', views.registerPage, name="register"),
    path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),
    path('home/', views.home, name="home"),
]

my template

    <form method="POST" action="{% url 'entry' %}">
    {% csrf_token %}
    Name

    <input type="text" name="name" class="form-control">

    Phone

    <input type="text" name="phone" class="form-control" >

    Email

    <input type="text" name="phone" class="form-control" >

    <input class="btn login_btn" type="submit" value="save">

</form>

Body:
You are not sending email field nor its value to your form

   <label for="">Email</label><br>
    <div class="input-group mb-2">
    <input type="text" name="phone" class="form-control" >
    </div>

as you can see name="phone" should be name="email" instead


问:
How to create and use a map in ReactJS
I have a Spring-Boot app with a ReactJS front-end, and I'm trying to figure out how to use Semantic UI to use a value selected from one input field to populate another input field.

I think I have most of the pieces in place, but I'm trying to figure out how to select a value from an array of name/value objects based on the name. I haven't quite gotten how the "map" function works, and the examples I've seen so far choose based on an index rather than a value. How to code it so it chooses the entry based on the value?

For example, here's the array:

```<code>const productMap = [
  {key: 'template_key1', value: 'Product 1'},
  {key: 'template_key2', value: 'Product 2'},
  {key: 'template_key3', value: 'Product 3'}
}
</code>```

I have a method that gets called when the user selects the key:

```<code> handleSelectTemplateChange=(event,{value})=>{
    let item = {...this.state.item};
    item.template = value;

    // how should this be coded?
    item.product = productMap.getValue(item.template);

    this.setState({item});
  }
</code>```

答:
You can use array find too. It is ideal to use find instead of map/forEach because we don't need to map over all the array elements once we find desired product.

const productMap = [
  { key: "template_key1", value: "Product 1"},
  { key: "template_key2", value: "Product 2" },
  { key: "template_key3", value: "Product 3" },
];

handleSelectTemplateChange = (event, { value }) => {
  let item = { ...this.state.item };
  item.template = value;
  const productValue = productMap.find((product) => product.key === value);
  item.product = productValue.value;
  this.setState({ item });
};

```

Title: How to create and use a map in ReactJS

Body:
I have a Spring-Boot app with a ReactJS front-end, and I'm trying to figure out how to use Semantic UI to use a value selected from one input field to populate another input field.

I think I have most of the pieces in place, but I'm trying to figure out how to select a value from an array of name/value objects based on the name. I haven't quite gotten how the "map" function works, and the examples I've seen so far choose based on an index rather than a value. How to code it so it chooses the entry based on the value?

For example, here's the array:

const productMap = [
  {key: 'template_key1', value: 'Product 1'},
  {key: 'template_key2', value: 'Product 2'},
  {key: 'template_key3', value: 'Product 3'}
}

I have a method that gets called when the user selects the key:

 handleSelectTemplateChange=(event,{value})=>{
    let item = {...this.state.item};
    item.template = value;

    // how should this be coded?
    item.product = productMap.getValue(item.template);

    this.setState({item});
  }


问:
asp.net DetailsView allowing ID / PK entry
I've got a DetailsView which is defaulted to insert mode:

```<code><asp:DetailsView runat="server" DataSourceID="SqlDataSource"
    AutoGenerateInsertButton="true" DefaultMode="Insert"
    DataKeyNames="ID"></asp:DetailsView>
</code>```

The issue being that the input for ID is editable, i.e. a user can input an ID. Entering an ID does nothing on the actual update command, but a user shouldn't think he can put their own ID in the first place. I don't have ID as an InputParameter nor is it included in the actual SQL command in the code-behind.

On a GridView that uses the same SqlDataSource, I easily disabled ID editing using the DataKeyNames="ID" attribute but this doesn't seem to have worked for the DetailsView - any ideas how to prevent a user editing the ID field?

EDIT:
I've just added an ID attribute, AutoGenerateRows="true" and EnableModelValidation="true" and still nothing preventing user from toying with the ID field.

答:
Here is an example from Microsoft Help:

```<code><asp:DetailsView ID="CustomerDetail"
        DataSourceID="Details" AutoGenerateRows="false"
        AutoGenerateInsertButton="true"
        AutoGenerateEditButton="true"
        AutoGenerateDeleteButton="true"
        EmptyDataText="No records."
        DataKeyNames="CustomerID" GridLines="Both"
        OnItemInserted="CustomerDetail_ItemInserted"
        OnItemInserting="CustomerDetail_ItemInserting"
        OnItemUpdated="CustomerDetail_ItemUpdated"
        OnItemUpdating="CustomerDetail_ItemUpdating"
        OnItemDeleted="CustomerDetail_ItemDeleted"
        runat="server">
        <HeaderStyle BackColor="Navy" ForeColor="White" />
        <RowStyle BackColor="White" />
        <AlternatingRowStyle BackColor="LightGray" />
        <EditRowStyle BackColor="LightCyan" />
        <Fields>
          <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" />
          <asp:BoundField DataField="ContactName" HeaderText="ContactName" />
          <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" />
          <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
          <asp:BoundField DataField="Address" HeaderText="Address" />
          <asp:BoundField DataField="City" HeaderText="City" />
          <asp:BoundField DataField="Region" HeaderText="Region" />
          <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
          <asp:BoundField DataField="Country" HeaderText="Country" />
          <asp:BoundField DataField="Phone" HeaderText="Phone" />
          <asp:BoundField DataField="Fax" HeaderText="Fax" />
        </Fields>
      </asp:DetailsView>
</code>```

Note under <Fields>, the first field has a ReadOnly="True" attribute. Try that.

Body:
I've got a DetailsView which is defaulted to insert mode:

<asp:DetailsView runat="server" DataSourceID="SqlDataSource"
    AutoGenerateInsertButton="true" DefaultMode="Insert"
    DataKeyNames="ID"></asp:DetailsView>

The issue being that the input for ID is editable, i.e. a user can input an ID. Entering an ID does nothing on the actual update command, but a user shouldn't think he can put their own ID in the first place. I don't have ID as an InputParameter nor is it included in the actual SQL command in the code-behind.

On a GridView that uses the same SqlDataSource, I easily disabled ID editing using the DataKeyNames="ID" attribute but this doesn't seem to have worked for the DetailsView - any ideas how to prevent a user editing the ID field?

EDIT:
I've just added an ID attribute, AutoGenerateRows="true" and EnableModelValidation="true" and still nothing preventing user from toying with the ID field.

Body:
Here is an example from Microsoft Help:

<asp:DetailsView ID="CustomerDetail"
        DataSourceID="Details" AutoGenerateRows="false"
        AutoGenerateInsertButton="true"
        AutoGenerateEditButton="true"
        AutoGenerateDeleteButton="true"
        EmptyDataText="No records."
        DataKeyNames="CustomerID" GridLines="Both"
        OnItemInserted="CustomerDetail_ItemInserted"
        OnItemInserting="CustomerDetail_ItemInserting"
        OnItemUpdated="CustomerDetail_ItemUpdated"
        OnItemUpdating="CustomerDetail_ItemUpdating"
        OnItemDeleted="CustomerDetail_ItemDeleted"
        runat="server">
        <HeaderStyle BackColor="Navy" ForeColor="White" />
        <RowStyle BackColor="White" />
        <AlternatingRowStyle BackColor="LightGray" />
        <EditRowStyle BackColor="LightCyan" />
        <Fields>
          <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" />
          <asp:BoundField DataField="ContactName" HeaderText="ContactName" />
          <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" />
          <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
          <asp:BoundField DataField="Address" HeaderText="Address" />
          <asp:BoundField DataField="City" HeaderText="City" />
          <asp:BoundField DataField="Region" HeaderText="Region" />
          <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
          <asp:BoundField DataField="Country" HeaderText="Country" />
          <asp:BoundField DataField="Phone" HeaderText="Phone" />
          <asp:BoundField DataField="Fax" HeaderText="Fax" />
        </Fields>
      </asp:DetailsView>

Note under <Fields>, the first field has a ReadOnly="True" attribute. Try that.


问:
Angular 9 Redirect if query param not provided
I have a route that should only be accessible to a user when they click a link from an email and are redirected with a valid query parameter in the url. If the parameter is not provided, I want to redirect to a 404 page not found component, like follows.

```<code>this.route.queryParams.subscribe(params => {
      if (params.myParam) {
        //do something
      } else {
        // redirect to 404
      }
    })
</code>```

The issue I have is that query params is initialized to an empty object in ngOnInit(). I have utilized rjxs to wait until the parameter is accessible like this

```<code>this.route.queryParamMap.pipe(
      filter(paramMap => paramMap.has('myParam')),
      map(paramMap => paramMap.get('myParam')),
      take(1)
    ).subscribe(myParam => doSomething(myParam));
</code>```

But I'm not very well versed in rxjs operators, and now I'm stuck on how to actually redirect if  paramMap has finished initializing and the parameter isn't found.

答:
In order to route to a 404 if the queryParam is not set, do:

```<code>import { Router } from '@angular/router'

class ...

constructor(private router: Router, private route: ActivatedRoute){
this.route.queryParamMap.pipe(
  skip(1),
  map(paramMap => paramMap.get('myParam')),
  tap(param=>{if(param=={} || param==undefined)this.router.navigateByUrl("/404.html")})
).subscribe(myParam => doSomething(myParam));

}
</code>```

You can start the subscription within the constructor, that way you will get the first value before it is modified in any other methods like ngOninit.

Body:
I have a route that should only be accessible to a user when they click a link from an email and are redirected with a valid query parameter in the url. If the parameter is not provided, I want to redirect to a 404 page not found component, like follows.

this.route.queryParams.subscribe(params => {
      if (params.myParam) {
        //do something
      } else {
        // redirect to 404
      }
    })

The issue I have is that query params is initialized to an empty object in ngOnInit(). I have utilized rjxs to wait until the parameter is accessible like this

this.route.queryParamMap.pipe(
      filter(paramMap => paramMap.has('myParam')),
      map(paramMap => paramMap.get('myParam')),
      take(1)
    ).subscribe(myParam => doSomething(myParam));

But I'm not very well versed in rxjs operators, and now I'm stuck on how to actually redirect if  paramMap has finished initializing and the parameter isn't found.

Body:
In order to route to a 404 if the queryParam is not set, do:

import { Router } from '@angular/router'

class ...

constructor(private router: Router, private route: ActivatedRoute){
this.route.queryParamMap.pipe(
  skip(1),
  map(paramMap => paramMap.get('myParam')),
  tap(param=>{if(param=={} || param==undefined)this.router.navigateByUrl("/404.html")})
).subscribe(myParam => doSomething(myParam));

}

You can start the subscription within the constructor, that way you will get the first value before it is modified in any other methods like ngOninit.