问:
MySQL doesn't set a default value while adding a new row to the table
I'm writing a web application (that represents online banking work). I have an entity "user" and a corresponding table in the database. Also, I have a registration form that transfers entered data via Thymeleaf.

My entity has two rows that have default values in the database. These are "role" row and "status". I set the default value in the database.

But, when I do input data in the registration form and click "sign up", the data transfers to the database successfully, however, two rows (role and status) that have their own default values are of a null type. Why the default values aren't being set automatically?

My entity class:

```<code>@Data
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "status")
    private Status status;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "role")
    private Role role;
}
</code>```

My settings in the database table:

When I check the property "NOT NULL", I'm receiving an error that tells me that the row "role" cannot be null.

That's how my table looks like when I register new users:

My controller:

```<code>@Controller
@RequestMapping("/auth")
public class AuthController {

    private final UserRepository userRepository;

    @Autowired
    public AuthController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @GetMapping("/signup")
    public String signUp(User user, Model model) {
        return "/auth/registration";
    }

    @PostMapping("/signup")
    public String signUpProcess(@ModelAttribute User user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "redirect:/auth/registration";
        }

        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(12);
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userRepository.save(user);

        return "redirect:/auth/login";
    }

}
</code>```

Registration page:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Registration</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/login.css">

    <form class="form-signin" th:method="post" th:object="${user}">

Registration

 Enter all the required information into the forms below.

            <input type="text" id="inputFirstName" th:field="*{firstName}" class="form-control" placeholder="First Name" required>
            First Name

            <input type="text" id="inputLastName" th:field="*{lastName}" class="form-control" placeholder="Last Name" required>
            Last Name

            <input type="email" id="inputEmail" th:field="*{email}" class="form-control" placeholder="Email address" required autofocus>
            Email address

            <input type="password" id="inputPassword" th:field="*{password}" class="form-control" placeholder="Password" required>
            Password

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>

Already registered? Click to sign in

© BlackBank 2022

    </form>

```
</div>
</div>
</p>
<p>If I haven't specified some valuable information, please, let me know.</p>
<p>Update:</p>
<p>SHOW CREATE TABLE:</p>
```CREATE TABLE `users` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(150) NOT NULL,
  `role` varchar(20) NOT NULL DEFAULT 'USER',
  `status` varchar(20) NOT NULL DEFAULT 'ACTIVE',
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_id_uindex` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
```
<p>My Role and Status classes (enums):</p>
<p>Role.class:</p>
```public enum Role {
    // Each role has a specific set of permissions
    USER(Set.of(Permission.USERS_READ)),
    ADMIN(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE)),
    OWNER(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE, Permission.USERS_DELETE));

    private Set<Permission> permissions;

    Role(Set<Permission> permissions) {
        this.permissions = permissions;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public Set<SimpleGrantedAuthority> getAuthorities() {
        return getPermissions().stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toSet());
    }

}
```
<p>Status.class:</p>
```public enum Status {
    ACTIVE, BANNED;
}
```

答:
@cloumn annotation should be something like below</p>
```<code>@Column(name = "status", nullable=false, length = 20, columnDefinition = "varchar(20) default 'ACTIVE'")
@Column(name = "role", nullable=false, length = 20, columnDefinition = "varchar(20) default 'USER'")
</code>```

Body:
I'm writing a web application (that represents online banking work). I have an entity "user" and a corresponding table in the database. Also, I have a registration form that transfers entered data via Thymeleaf.

My entity has two rows that have default values in the database. These are "role" row and "status". I set the default value in the database.

But, when I do input data in the registration form and click "sign up", the data transfers to the database successfully, however, two rows (role and status) that have their own default values are of a null type. Why the default values aren't being set automatically?

My entity class:

@Data
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "status")
    private Status status;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "role")
    private Role role;
}

My settings in the database table:

When I check the property "NOT NULL", I'm receiving an error that tells me that the row "role" cannot be null.

That's how my table looks like when I register new users:

My controller:

@Controller
@RequestMapping("/auth")
public class AuthController {

    private final UserRepository userRepository;

    @Autowired
    public AuthController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @GetMapping("/signup")
    public String signUp(User user, Model model) {
        return "/auth/registration";
    }

    @PostMapping("/signup")
    public String signUpProcess(@ModelAttribute User user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "redirect:/auth/registration";
        }

        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(12);
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userRepository.save(user);

        return "redirect:/auth/login";
    }

}

Registration page:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Registration</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/login.css">

    <form class="form-signin" th:method="post" th:object="${user}">

Registration

 Enter all the required information into the forms below.

            <input type="text" id="inputFirstName" th:field="*{firstName}" class="form-control" placeholder="First Name" required>
            First Name

            <input type="text" id="inputLastName" th:field="*{lastName}" class="form-control" placeholder="Last Name" required>
            Last Name

            <input type="email" id="inputEmail" th:field="*{email}" class="form-control" placeholder="Email address" required autofocus>
            Email address

            <input type="password" id="inputPassword" th:field="*{password}" class="form-control" placeholder="Password" required>
            Password

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>

Already registered? Click to sign in

© BlackBank 2022

    </form>

If I haven't specified some valuable information, please, let me know.

Update:

SHOW CREATE TABLE:

CREATE TABLE `users` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(150) NOT NULL,
  `role` varchar(20) NOT NULL DEFAULT 'USER',
  `status` varchar(20) NOT NULL DEFAULT 'ACTIVE',
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_id_uindex` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

My Role and Status classes (enums):

Role.class:

public enum Role {
    // Each role has a specific set of permissions
    USER(Set.of(Permission.USERS_READ)),
    ADMIN(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE)),
    OWNER(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE, Permission.USERS_DELETE));

    private Set<Permission> permissions;

    Role(Set<Permission> permissions) {
        this.permissions = permissions;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public Set<SimpleGrantedAuthority> getAuthorities() {
        return getPermissions().stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toSet());
    }

}

Status.class:

public enum Status {
    ACTIVE, BANNED;
}

Body:
@cloumn annotation should be something like below

@Column(name = "status", nullable=false, length = 20, columnDefinition = "varchar(20) default 'ACTIVE'")
@Column(name = "role", nullable=false, length = 20, columnDefinition = "varchar(20) default 'USER'")


来源: stackexchange

问:
Disable (exclude) bootstrap for one div on a page
I have an application that pulls custom old emails and displays them on a page in DOM. I want to exclude a div that contains this HTML email from bootstrap css. Something like this: </p>

```<code><div class="email_container">
<!-- bootstrap CSS shouldn't apply here-->
<div class="email">
<!-- neither here-->
</div>
</div>
</code>```

<p>Is there a way this can be done? I did some research and saw people talking about LESS and SASS to solve this but is there a way to do this without them as I don't want to include LESS or SASS in my project just for this purpose. </p>

答:
One quick and dirty way to achieve this is to recompile the whole bootstrap stylesheets with a CSS preprocessor after wrapping it into a CSS class like :

```<code>.bootstap-include{
   /* Content of bootstap.css .. */
}
</code>```

To make it work, the file needs some tweaks :

Replace the :root selector at the top of the file with a &

Replace the body selector at the top of the file with a &

Remove the charset declaration @charset "UTF-8";

See a working pen here : https://codepen.io/kisaure/pen/WNXOBdz

I didn't test it but I think bootsrap.js functions and some other stuff may be broken.

ContentLicense: CC BY-SA 3.0

Body:
I have an application that pulls custom old emails and displays them on a page in DOM. I want to exclude a div that contains this HTML email from bootstrap css. Something like this:

Is there a way this can be done? I did some research and saw people talking about LESS and SASS to solve this but is there a way to do this without them as I don't want to include LESS or SASS in my project just for this purpose.

Body:
One quick and dirty way to achieve this is to recompile the whole bootstrap stylesheets with a CSS preprocessor after wrapping it into a CSS class like :

.bootstap-include{
   /* Content of bootstap.css .. */
}

To make it work, the file needs some tweaks :

Replace the :root selector at the top of the file with a &

Replace the body selector at the top of the file with a &

Remove the charset declaration @charset "UTF-8";

See a working pen here : https://codepen.io/kisaure/pen/WNXOBdz

I didn't test it but I think bootsrap.js functions and some other stuff may be broken.

ContentLicense: CC BY-SA 4.0


问:
determine trajectory for object followers - curve of pursuit
I have started to develop unit trajectories for a game server and for now I'm trying to retrieve the position of a unit at a given time. It is easy when the trajectory is just a straight line, but it is far more complicated when unit chases another unit.

I've done flash app to illustrate the problem. Black trajectory is for unit which travels in a single direction. Blue chases black and red chases blue. What I want is to precalculate whole trajectory for blue and red to be able to retrieve their position in a constant time.

Is it possible? Thanks for any help!!

答:
I can set up the problem for you but not solve it.

The black curve is moving at a constant velocity v0, and in a straight line.

The blue curve moves at a constant velocity v1 in the direction of black.

For simplicity, choose coordinates so that at time t=0 the black curve starts at (x=0, y=0) and is moving in the direction x.

Thus, at time t >= 0, the position of the black curve is (v0 t, 0).

Problem statement

The goal is to find x, y of the blue curve for times t >= 0 given the initial position (x(t=0), y(t=0)). The differential equations of motion are

dx / dt = v1 (v0 t - x) / a(t)

dy / dt = v1 (- y) / a(t)

where a(t) = sqrt((v0 t - x)^2 + (y^2)) is the distance between blue and black at time t.

This is a system of two nonlinear coupled differential equations. It seems likely that there is no complete anaytical solution. Wolfram Alpha gives up without trying for the input

```<code>D[y[t],t] = -y[t] / sqrt[(t-x[t])^2 + y[t]^2], D[x[t],t] = (t-x[t]) / sqrt[(t-x[t])^2 + y[t]^2]
</code>```

You could try asking on math.stackexchange. Good luck!

Body:
I can set up the problem for you but not solve it.

The black curve is moving at a constant velocity v0, and in a straight line.

The blue curve moves at a constant velocity v1 in the direction of black.

For simplicity, choose coordinates so that at time t=0 the black curve starts at (x=0, y=0) and is moving in the direction x.

Thus, at time t >= 0, the position of the black curve is (v0 t, 0).

Problem statement

The goal is to find x, y of the blue curve for times t >= 0 given the initial position (x(t=0), y(t=0)). The differential equations of motion are

dx / dt = v1 (v0 t - x) / a(t)

dy / dt = v1 (- y) / a(t)

where a(t) = sqrt((v0 t - x)^2 + (y^2)) is the distance between blue and black at time t.

This is a system of two nonlinear coupled differential equations. It seems likely that there is no complete anaytical solution. Wolfram Alpha gives up without trying for the input

D[y[t],t] = -y[t] / sqrt[(t-x[t])^2 + y[t]^2], D[x[t],t] = (t-x[t]) / sqrt[(t-x[t])^2 + y[t]^2]

You could try asking on math.stackexchange. Good luck!


问:
HTML5 pattern phone number In Egypt
What regex do I need to put into pattern to make sure the inputted number start with "011", "012" or "010" and then 8 digits?
Example of wanted output:

012 XXXXXXXX

011 XXXXXXXX

010 XXXXXXXX

Note : X is any number from [0-9].

```<code><input type="number" pattern="" required />
</code>```

Title: HTML5 pattern phone number In Egypt

Body:
What regex do I need to put into pattern to make sure the inputted number start with "011", "012" or "010" and then 8 digits?
Example of wanted output:

012 XXXXXXXX

011 XXXXXXXX

010 XXXXXXXX

Note : X is any number from [0-9].

<input type="number" pattern="" required />

Body:
Just use this Regexp:

/^01[0125][0-9]{8}$/


问:
Days tracker in excel, until closure date or today?
I have a spreadsheet with these 3 columns

starting date (has to have a value)

closing date (can have a value or be blank)

days passed (actual days, weekends and such included)

I would like to know which formula i can use to have this result:

If (2) is blank, then (3) has to show the date difference between today and (1), obviously updating every day

If (2) has a valid value,then (3) should be the date differenze betweeen (2) and (1)

Thanks in advance

答:
Try this:

If A2 has starting date, and B2 has closing date, place this in C2:

```<code>=IF(ISBLANK( B2),TODAY()-A2,B2-A2)
</code>```

Body:
Try this:

If A2 has starting date, and B2 has closing date, place this in C2:

=IF(ISBLANK( B2),TODAY()-A2,B2-A2)


问:
Flask heroku app won't let me assign some config settings
I have a flask MySql app that is working correctly on local, but when I deployed to heroku it gives me below error:

```<code>2022-02-12T05:28:26.114583+00:00 app[web.1]: File "/app/app.py", line 38, in <module>
2022-02-12T05:28:26.114583+00:00 app[web.1]: app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
2022-02-12T05:28:26.114584+00:00 app[web.1]: TypeError: 'str' object does not support item assignment
</code>```

It did the same thing when I used app.debug = False. I tried to fix it my removing it, but now it gives me above error.

I tried commenting each line that gives error and looks like all below lines give the same error:

```<code>app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_TYPE'] = "filesystem"
</code>```

Few lines before these lines I have app.config['MAIL_USE_SSL'] = True and some other mail config settings (port, server, username, password) which none of them give error, so I don't understand what the problem is. When I google the error it is related with the immutability of strings, so I don't understand what is the problem on my case.

When I comment all of the above it gives me:

```<code>2022-02-12T08:11:34.109191+00:00 app[web.1]: Session(app)
2022-02-12T08:11:34.109196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/flask_session/__init__.py", line 54, in __init__
2022-02-12T08:11:34.109196+00:00 app[web.1]: self.init_app(app)
2022-02-12T08:11:34.109196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/flask_session/__init__.py", line 61, in init_app
2022-02-12T08:11:34.109197+00:00 app[web.1]: app.session_interface = self._get_interface(app)
2022-02-12T08:11:34.109197+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/flask_session/__init__.py", line 64, in _get_interface
2022-02-12T08:11:34.109197+00:00 app[web.1]: config = app.config.copy()
2022-02-12T08:11:34.109198+00:00 app[web.1]: AttributeError: 'str' object has no attribute 'copy'
</code>```

I'm using JawsDB MySQL addon on heroku if that is related with this issue.

Below is the code:

from flask import Flask
from flask_mail import Mail
from os import environ
from flask_session import Session
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.domain.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = "mail@domain.com"
app.config['MAIL_PASSWORD'] = environ.get("MAIL_PASSWORD")
mail = Mail(app)

MY_APP_ENV = environ.get("MY_APP_ENV")
if MY_APP_ENV == 'prod':
    app.debug = False
    app.config = environ.get("JAWSDB_URL")
else:
    app.debug = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/my_app'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_TYPE'] = "filesystem"
Session(app)
CORS(app)

db = SQLAlchemy(app)
# rest is the routings etc.
```

答:
Here's the problem:

```<code>app.config = environ.get("JAWSDB_URL")
</code>```

You are overwriting app.config with a single value from the environment.

Do you mean something like this instead?

```<code>app.config["SQLALCHEMY_DATABASE_URI"] = environ.get("JAWSDB_URL")
</code>```

Body:
I have a flask MySql app that is working correctly on local, but when I deployed to heroku it gives me below error:

2022-02-12T05:28:26.114583+00:00 app[web.1]: File "/app/app.py", line 38, in <module>
2022-02-12T05:28:26.114583+00:00 app[web.1]: app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
2022-02-12T05:28:26.114584+00:00 app[web.1]: TypeError: 'str' object does not support item assignment

It did the same thing when I used app.debug = False. I tried to fix it my removing it, but now it gives me above error.

I tried commenting each line that gives error and looks like all below lines give the same error:

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_TYPE'] = "filesystem"

Few lines before these lines I have app.config['MAIL_USE_SSL'] = True and some other mail config settings (port, server, username, password) which none of them give error, so I don't understand what the problem is. When I google the error it is related with the immutability of strings, so I don't understand what is the problem on my case.

When I comment all of the above it gives me:

2022-02-12T08:11:34.109191+00:00 app[web.1]: Session(app)
2022-02-12T08:11:34.109196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/flask_session/__init__.py", line 54, in __init__
2022-02-12T08:11:34.109196+00:00 app[web.1]: self.init_app(app)
2022-02-12T08:11:34.109196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/flask_session/__init__.py", line 61, in init_app
2022-02-12T08:11:34.109197+00:00 app[web.1]: app.session_interface = self._get_interface(app)
2022-02-12T08:11:34.109197+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/flask_session/__init__.py", line 64, in _get_interface
2022-02-12T08:11:34.109197+00:00 app[web.1]: config = app.config.copy()
2022-02-12T08:11:34.109198+00:00 app[web.1]: AttributeError: 'str' object has no attribute 'copy'

I'm using JawsDB MySQL addon on heroku if that is related with this issue.

Below is the code:

from flask import Flask
from flask_mail import Mail
from os import environ
from flask_session import Session
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.domain.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = "mail@domain.com"
app.config['MAIL_PASSWORD'] = environ.get("MAIL_PASSWORD")
mail = Mail(app)

MY_APP_ENV = environ.get("MY_APP_ENV")
if MY_APP_ENV == 'prod':
    app.debug = False
    app.config = environ.get("JAWSDB_URL")
else:
    app.debug = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/my_app'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_TYPE'] = "filesystem"
Session(app)
CORS(app)

db = SQLAlchemy(app)
# rest is the routings etc.

Body:
Here's the problem:

app.config = environ.get("JAWSDB_URL")

You are overwriting app.config with a single value from the environment.

Do you mean something like this instead?

app.config["SQLALCHEMY_DATABASE_URI"] = environ.get("JAWSDB_URL")


问:
load static and DOCTYPE html position in django views
I am new to Django and have trouble understanding the difference between the position of lines shown below:

```<code>{% load static %}
<!DOCTYPE html>
</code>```

In the above code, the PyCharm shows error but if I change the position as shown below, it works as intended:

```<code><!DOCTYPE html>
{% load static %}
</code>```

Can anyone explain how this works or if I am doing it the wrong way? Thanks!!

答:
You need to add an extension named "Django templates" in your vs-code or any other editor you are using.
[
After This: Your Code will look like this with No warning:-

Body:
I am new to Django and have trouble understanding the difference between the position of lines shown below:

{% load static %}
<!DOCTYPE html>

In the above code, the PyCharm shows error but if I change the position as shown below, it works as intended:

<!DOCTYPE html>
{% load static %}

Can anyone explain how this works or if I am doing it the wrong way? Thanks!!


问:
Finding json attribute by wildard with jq
I am trying to find a way to extract JSON attributes using wildcard selection with jq. Is there any way to do it? I have the following JSON file.  The fields can be dynamic for each system. I want to map Core with its "input" temperature (tempX_input).

{
  "Core 0": {
    "temp2_input": "52.000",
    "temp2_max": "100.000",
    "temp2_crit": "100.000",
    "temp2_crit_alarm": "0.000"
  },
  "Core 1": {
    "temp3_input": "53.000",
    "temp3_max": "100.000",
    "temp3_crit": "100.000",
    "temp3_crit_alarm": "0.000"
  }
}
```
<p><strong>Result:</strong></p>
<pre class="lang-json prettyprint-override"><code>{
  "Core 0": "52.000",
  "Core 1": "53.000"
}
</code>```

答:
You could use:

```<code>with_entries(.value |= (with_entries(select(.key | endswith("_input"))) | to_entries[].value ))
</code>```

Using with_enries so we can get the desired keys using endswith("_input")

The above will generate:

{
  "Core 0": 52,
  "Core 1": 53
}
```

As you can test in this online demo

Body:
I am trying to find a way to extract JSON attributes using wildcard selection with jq. Is there any way to do it? I have the following JSON file.  The fields can be dynamic for each system. I want to map Core with its "input" temperature (tempX_input).

{
  "Core 0": {
    "temp2_input": "52.000",
    "temp2_max": "100.000",
    "temp2_crit": "100.000",
    "temp2_crit_alarm": "0.000"
  },
  "Core 1": {
    "temp3_input": "53.000",
    "temp3_max": "100.000",
    "temp3_crit": "100.000",
    "temp3_crit_alarm": "0.000"
  }
}

Result:

{
  "Core 0": "52.000",
  "Core 1": "53.000"
}

Body:
You could use:

with_entries(.value |= (with_entries(select(.key | endswith("_input"))) | to_entries[].value ))

Using with_enries so we can get the desired keys using endswith("_input")

The above will generate:

{
  "Core 0": 52,
  "Core 1": 53
}

As you can test in this online demo


问:
The file_date function creates a new file in the current working directory,
```<code>import os
import datetime

def file_date(filename):
  # Create the file in the current directory
  ___
  timestamp = ___
  # Convert the timestamp into a readable format, then into a string
  ___
  # Return just the date portion
  # Hint: how many characters are in “yyyy-mm-dd”?
  return ("{___}".format(___))

print(file_date("newfile.txt"))
</code>```

Should be today's date in the format of yyyy-mm-dd

答:
```<code>import os
from datetime import datetime

def file_date(filename):
    # Create the file in the current directory
    fp = open(filename, 'w')
    timestamp = os.path.getmtime(filename)
    fp.close()
    # Convert the timestamp into a readable format, then into a string
    readable = datetime.fromtimestamp(timestamp)
    string = readable.strftime('%Y-%m-%d %H:%M:%S')

    # Return just the date portion
    # Hint: how many characters are in “yyyy-mm-dd”?
    s1 = slice(10)
    return(string[s1])

print(file_date("newfile.txt"))
# Should be today's date in the format of yyyy-mm-dd

</code>```

Output will be like 2022-02-12

Body:
import os
import datetime

def file_date(filename):
  # Create the file in the current directory
  ___
  timestamp = ___
  # Convert the timestamp into a readable format, then into a string
  ___
  # Return just the date portion
  # Hint: how many characters are in “yyyy-mm-dd”?
  return ("{___}".format(___))

print(file_date("newfile.txt"))

Should be today's date in the format of yyyy-mm-dd

Body:
import os
from datetime import datetime

def file_date(filename):
    # Create the file in the current directory
    fp = open(filename, 'w')
    timestamp = os.path.getmtime(filename)
    fp.close()
    # Convert the timestamp into a readable format, then into a string
    readable = datetime.fromtimestamp(timestamp)
    string = readable.strftime('%Y-%m-%d %H:%M:%S')

    # Return just the date portion
    # Hint: how many characters are in “yyyy-mm-dd”?
    s1 = slice(10)
    return(string[s1])

print(file_date("newfile.txt"))
# Should be today's date in the format of yyyy-mm-dd

Output will be like 2022-02-12


问:
Customize multiple mui components
From MUI's docs you have the ability to customize a component. But is there a way to customize multiple components?
Say I want to customize MuiPaper and MuiList with the same styles.

E.g of customizable components:

```<code>const theme = createTheme({
  components: {
    // Name of the component
    MuiPaper: {
      defaultProps: {
        // The props to change the default for.
        backgroundColor: '#101010',
      },
    },
  },
});
</code>```

答:
there are multiple ways to customize the default props. please check below I have added three ways to customize the components. also you can add more components to it.

theme.js

```<code>const mytheme = {
  components: {
    MuiPaper: {
      styleOverrides: {
        root: ({ theme }) => ({ // using with theme
          backgroundColor: theme.palette.primary.main,
          color: theme.palette.primary.contrastText,
        }),
      },
    },
    MuiList : {
      styleOverrides: {
        root: { // adding direct CSS properties with screensize condition.
          '@media (min-width:600px)': {
            minHeight: '4.5rem',
            backgroundColor: '#101010',
          },
        },
      },
    },
    MuiButton: {
      styleOverrides: {
        root: ({ ownerState, theme }) => ({ // changing only 'contained' variant or adding new variant.
        textTransform: 'capitalize',
         ...(ownerState.variant === 'contained' && {
            color: theme.palette.primary.contrastText,
            backgroundColor: theme.palette.primary.light,
          }),
        }),
      },
    },
  },
};

export default mytheme;
</code>```

app.js

```<code>const App = () => {
  <ThemeProvider theme={createTheme(mytheme)}>
    ...
  </ThemeProvider>
}
export default App;
</code>```

Title: Customize multiple mui components

Body:
From MUI's docs you have the ability to customize a component. But is there a way to customize multiple components?
Say I want to customize MuiPaper and MuiList with the same styles.

E.g of customizable components:

const theme = createTheme({
  components: {
    // Name of the component
    MuiPaper: {
      defaultProps: {
        // The props to change the default for.
        backgroundColor: '#101010',
      },
    },
  },
});

Body:
there are multiple ways to customize the default props. please check below I have added three ways to customize the components. also you can add more components to it.

theme.js

const mytheme = {
  components: {
    MuiPaper: {
      styleOverrides: {
        root: ({ theme }) => ({ // using with theme
          backgroundColor: theme.palette.primary.main,
          color: theme.palette.primary.contrastText,
        }),
      },
    },
    MuiList : {
      styleOverrides: {
        root: { // adding direct CSS properties with screensize condition.
          '@media (min-width:600px)': {
            minHeight: '4.5rem',
            backgroundColor: '#101010',
          },
        },
      },
    },
    MuiButton: {
      styleOverrides: {
        root: ({ ownerState, theme }) => ({ // changing only 'contained' variant or adding new variant.
        textTransform: 'capitalize',
         ...(ownerState.variant === 'contained' && {
            color: theme.palette.primary.contrastText,
            backgroundColor: theme.palette.primary.light,
          }),
        }),
      },
    },
  },
};

export default mytheme;

app.js

const App = () => {
  <ThemeProvider theme={createTheme(mytheme)}>
    ...
  </ThemeProvider>
}
export default App;


问:
Do we still use api endpoint health check in Kubernetes
I want to use API endpoint health check like /healthz or /livez or /readyz.
I recently heard about it, tried to search but didn't find any place which tell me how we use it.
I see that /healthz is deprecated.
Can you tell me if have to use it in a pod definition file or we have to use it in code.
I have a basic hello world app.
can some one help me understand it and tell me where does it fit in ?

```<code>import time
import os

import redis
from flask import Flask

from flask_basicauth import BasicAuth

app = Flask(__name__)
cache = redis.Redis(host=os.environ['REDIS_HOST'], port=os.environ['REDIS_PORT'])

app.config['BASIC_AUTH_USERNAME'] = os.environ['USERNAME']
app.config['BASIC_AUTH_PASSWORD'] = os.environ['PASSWORD']

basic_auth = BasicAuth(app)

def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I have been seen {} times.\n'.format(count)

@app.route('/supersecret')
@basic_auth.required
def secret_view():
    count = get_hit_count()
    return os.environ['THEBIGSECRET']+ '\n'
</code>```

I already tried something like below and it seems working but if I use /supersecret instead of / it is not working

```<code>        readinessProbe:
          httpGet:
            path: /
            port: 5000
          initialDelaySeconds: 20
          periodSeconds: 5
        livenessProbe:
        httpGet:
          path: /
          port: 5000
        intialDelaySeconds: 30
        periodSeconds: 5
</code>```

答:
You can refer to these docs for an explanation of how "health checks", or probes as they're called in Kubernetes, work. For your question you may be particularly interested in the section on HTTP probes.

You can pick any HTTP path of your application for these probes, while indeed /healthz, /livez and /readyz are common ones and happen to be the ones used by the Kubernetes API server (with, as you found, the /healthz one being deprecated in favour of the more specific alternatives).

So, to implement health probes, simply add a GET route for each of the probes you'd like to the application and make sure the status code returned is 2xx or 3xx to signal a healthy state, or anything else when Kubernetes should consider the application unhealthy.

Any code greater than or equal to 200 and less than 400 indicates success. Any other code indicates failure.

In my opinion, it makes sense to return HTTP 200 for success and 500 or 503 for failure.

Once your application is set up to respond accordingly to the prober, you should instruct Kubernetes to use it by adding something along the following lines to the container exposing your API in the PodSpec:

    livenessProbe:
      httpGet:
        path: /your-liveness-probe-path
        port: 8080
```
<hr />
<p>If I understood your question regarding the probe failing for the <code>/supersecret</code> path, ignoring the indentation error in your YAML definition, this is most likely because that route requires authentication. The probes you have defined do not supply that. For this, you may use <code>httpHeaders</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>        readinessProbe:
          httpGet:
            path: /
            port: 5000
            httpHeaders:
            - name: Authorization
              value: "Bearer secret"
          initialDelaySeconds: 20
          periodSeconds: 5
</code>```

However, it is in my experience more common to not require authentication for your probe routes, but instead, to not expose those to the public internet (or even on a separate port). How to accomplish that is a whole different story and depends on how you are exposing your application in the first place, but one way could be to have an ingress with appropriate "ingress rules".

On a more general note about troubleshooting failing probes: running kubectl get events is a good starting point.

Body:
I want to use API endpoint health check like /healthz or /livez or /readyz.
I recently heard about it, tried to search but didn't find any place which tell me how we use it.
I see that /healthz is deprecated.
Can you tell me if have to use it in a pod definition file or we have to use it in code.
I have a basic hello world app.
can some one help me understand it and tell me where does it fit in ?

import time
import os

import redis
from flask import Flask

from flask_basicauth import BasicAuth

app = Flask(__name__)
cache = redis.Redis(host=os.environ['REDIS_HOST'], port=os.environ['REDIS_PORT'])

app.config['BASIC_AUTH_USERNAME'] = os.environ['USERNAME']
app.config['BASIC_AUTH_PASSWORD'] = os.environ['PASSWORD']

basic_auth = BasicAuth(app)

def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I have been seen {} times.\n'.format(count)

@app.route('/supersecret')
@basic_auth.required
def secret_view():
    count = get_hit_count()
    return os.environ['THEBIGSECRET']+ '\n'

I already tried something like below and it seems working but if I use /supersecret instead of / it is not working

        readinessProbe:
          httpGet:
            path: /
            port: 5000
          initialDelaySeconds: 20
          periodSeconds: 5
        livenessProbe:
        httpGet:
          path: /
          port: 5000
        intialDelaySeconds: 30
        periodSeconds: 5

Body:
You can refer to these docs for an explanation of how "health checks", or probes as they're called in Kubernetes, work. For your question you may be particularly interested in the section on HTTP probes.

You can pick any HTTP path of your application for these probes, while indeed /healthz, /livez and /readyz are common ones and happen to be the ones used by the Kubernetes API server (with, as you found, the /healthz one being deprecated in favour of the more specific alternatives).

So, to implement health probes, simply add a GET route for each of the probes you'd like to the application and make sure the status code returned is 2xx or 3xx to signal a healthy state, or anything else when Kubernetes should consider the application unhealthy.

Any code greater than or equal to 200 and less than 400 indicates success. Any other code indicates failure.

In my opinion, it makes sense to return HTTP 200 for success and 500 or 503 for failure.

Once your application is set up to respond accordingly to the prober, you should instruct Kubernetes to use it by adding something along the following lines to the container exposing your API in the PodSpec:

    livenessProbe:
      httpGet:
        path: /your-liveness-probe-path
        port: 8080

If I understood your question regarding the probe failing for the /supersecret path, ignoring the indentation error in your YAML definition, this is most likely because that route requires authentication. The probes you have defined do not supply that. For this, you may use httpHeaders:

        readinessProbe:
          httpGet:
            path: /
            port: 5000
            httpHeaders:
            - name: Authorization
              value: "Bearer secret"
          initialDelaySeconds: 20
          periodSeconds: 5

However, it is in my experience more common to not require authentication for your probe routes, but instead, to not expose those to the public internet (or even on a separate port). How to accomplish that is a whole different story and depends on how you are exposing your application in the first place, but one way could be to have an ingress with appropriate "ingress rules".

On a more general note about troubleshooting failing probes: running kubectl get events is a good starting point.


问:
How to get lastInsertID when executing a Stored Procedure on a mySQL Server in PHP?
Method 1 works fine for a standard prepared Query (I believe that's what its called) but I can't get either method 2 or 3 to return a LastInsertID - similar but different and not sure of advantages of either.

My main thing at this stage is getting the LastInsertID when using a Stored Procedure.

MySQL Table

```<code>CREATE TABLE `forms` (
  `FORM_ID` bigint(20) NOT NULL,
  `OUID` bigint(20) NOT NULL,
  `OID` bigint(20) NOT NULL,
  `UPDATED_DATE` timestamp NOT NULL DEFAULT current_timestamp(),
  `FORM_JSON` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`FORM_JSON`))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
</code>```

MySQL Stored Procedure- for Methods 2 & 3

```<code>DROP PROCEDURE `FORM_SAVEAS`;
CREATE DEFINER=`root`@`localhost` PROCEDURE `FORM_SAVEAS`
(IN `V_OUID` INT, IN `V_OID` INT, IN `V_FORM_JSON` JSON)
NOT DETERMINISTIC NO SQL SQL SECURITY DEFINER INSERT INTO `forms`
(OUID ,OID ,FORM_JSON )
VALUEs (V_OUID ,V_OID ,V_FORM_JSON)
</code>```

Method 1) Prepared statement(This Works - returns LastInsertID ok) - but I'd like to use a Stored Proc

```<code><?php

$V_OUID      = 1;
$V_OID       = 2;
$V_FORM_JSON = '{"var1":"data 1","var2":"Data two","var3":"DATA III"}';

include('database_connection.php');

$query = "INSERT INTO forms (OUID       , OID    , FORM_JSON)
                     VALUES ($V_OUID    , $V_OID , '" . $V_FORM_JSON . "')";

echo "The Query : $query";
try{
  $DB_CON -> exec($query);
  $form_id = $DB_CON->lastInsertId();
  echo "New Record created Successfully ID is: " . $form_id;
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
  echo $query;
}
</code>```

Method 2) This Inserts the data but doesn't return the lastInsertId

```<code><?php

$V_OUID      = 1;
$V_OID       = 2;
$V_FORM_JSON = '{"var1":"data 1","var2":"Data two","var3":"DATA III"}';

include('database_connection.php');

$query = "CALL FORM_SAVEAS($V_OUID    , $V_OID , '" . $V_FORM_JSON . "')";

echo "The Query : $query";
try{
  $DB_CON -> exec($query);
  $form_id = $DB_CON->lastInsertId();
  echo "New Record created Successfully ID is: " . $form_id;
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
  echo $query;
}

?>

</code>```

Method 3) This also Inserts the data but doesn't return the lastInsertId

```<code><?php

$V_OUID      = 1;
$V_OID       = 2;
$V_FORM_JSON = '{"var1":"data 1","var2":"Data two","var3":"DATA III"}';

include('database_connection.php');

$statement = $DB_CON->prepare('CALL FORM_SAVEAS(:V_OUID,:V_OID,:V_FORM_JSON)');
$statement->bindParam(':V_OUID', $V_OUID, PDO::PARAM_STR);
$statement->bindParam(':V_OID', $V_OID, PDO::PARAM_STR);
$statement->bindParam(':V_FORM_JSON', $V_FORM_JSON, PDO::PARAM_STR);
$statement->execute();
$form_id = $DB_CON->lastInsertID();

echo "New Record created Successfully ID is: " . $form_id;

?>
</code>```

Of methods 2 & 3 which is best or is there a better way?

答:
Lots of confusing information on this subject throughout the Web.
To put it simply, in your stored procedure, after you have completed your insert query (into what we'll cal "YourTable"), end it with a semi-colon, then do a select on that table, with the following:

SELECT LAST_INSERT_ID() AS WhateverVariableYouChose
FROM YourTable;

That ID is then returned, just as any select. So, in your PHP, you simply do

$R = $stmt->fetch();
$LastInsert = $R[WhateverVariableYouChose];

Body:
Method 1 works fine for a standard prepared Query (I believe that's what its called) but I can't get either method 2 or 3 to return a LastInsertID - similar but different and not sure of advantages of either.

My main thing at this stage is getting the LastInsertID when using a Stored Procedure.

MySQL Table

CREATE TABLE `forms` (
  `FORM_ID` bigint(20) NOT NULL,
  `OUID` bigint(20) NOT NULL,
  `OID` bigint(20) NOT NULL,
  `UPDATED_DATE` timestamp NOT NULL DEFAULT current_timestamp(),
  `FORM_JSON` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`FORM_JSON`))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

MySQL Stored Procedure- for Methods 2 & 3

DROP PROCEDURE `FORM_SAVEAS`;
CREATE DEFINER=`root`@`localhost` PROCEDURE `FORM_SAVEAS`
(IN `V_OUID` INT, IN `V_OID` INT, IN `V_FORM_JSON` JSON)
NOT DETERMINISTIC NO SQL SQL SECURITY DEFINER INSERT INTO `forms`
(OUID ,OID ,FORM_JSON )
VALUEs (V_OUID ,V_OID ,V_FORM_JSON)

Method 1) Prepared statement(This Works - returns LastInsertID ok) - but I'd like to use a Stored Proc

<?php

$V_OUID      = 1;
$V_OID       = 2;
$V_FORM_JSON = '{"var1":"data 1","var2":"Data two","var3":"DATA III"}';

include('database_connection.php');

$query = "INSERT INTO forms (OUID       , OID    , FORM_JSON)
                     VALUES ($V_OUID    , $V_OID , '" . $V_FORM_JSON . "')";

echo "The Query : $query";
try{
  $DB_CON -> exec($query);
  $form_id = $DB_CON->lastInsertId();
  echo "New Record created Successfully ID is: " . $form_id;
} catch(PDOException $e) {
  echo $sql . "
" . $e->getMessage();
  echo $query;
}

Method 2) This Inserts the data but doesn't return the lastInsertId

<?php

$V_OUID      = 1;
$V_OID       = 2;
$V_FORM_JSON = '{"var1":"data 1","var2":"Data two","var3":"DATA III"}';

include('database_connection.php');

$query = "CALL FORM_SAVEAS($V_OUID    , $V_OID , '" . $V_FORM_JSON . "')";

echo "The Query : $query";
try{
  $DB_CON -> exec($query);
  $form_id = $DB_CON->lastInsertId();
  echo "New Record created Successfully ID is: " . $form_id;
} catch(PDOException $e) {
  echo $sql . "
" . $e->getMessage();
  echo $query;
}

?>

Method 3) This also Inserts the data but doesn't return the lastInsertId

<?php

$V_OUID      = 1;
$V_OID       = 2;
$V_FORM_JSON = '{"var1":"data 1","var2":"Data two","var3":"DATA III"}';

include('database_connection.php');

$statement = $DB_CON->prepare('CALL FORM_SAVEAS(:V_OUID,:V_OID,:V_FORM_JSON)');
$statement->bindParam(':V_OUID', $V_OUID, PDO::PARAM_STR);
$statement->bindParam(':V_OID', $V_OID, PDO::PARAM_STR);
$statement->bindParam(':V_FORM_JSON', $V_FORM_JSON, PDO::PARAM_STR);
$statement->execute();
$form_id = $DB_CON->lastInsertID();

echo "New Record created Successfully ID is: " . $form_id;

?>

Of methods 2 & 3 which is best or is there a better way?


问:
Unable to Pass UUID string to API endpoint using POSTMAN Correctly
The API endpoint is something like that, at django backend
/accounts/id/uuid:pk/some_action/

in the models it is defined as

```<code>id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
</code>```

The apiview accepts requests and pk which is uuid as pk.

```<code>@api_view(['PUT'])
def some_action(request, pk):
</code>```

when i'm making a request with uuid it is giving me following error

```<code>Not Found: /accounts/user/{id}/some-action/
[12/Feb/2022 18:41:28] "PUT /accounts/id/%7Bid%7D/some-action/ HTTP/1.1" 404 4930
</code>```

in Postman i configure the url like this /accounts/id/{id}/some-action/

So what might be the problem in passing the uuid ?

答:
Please change the the url in the urls.py to /accounts/id/<uuid:pk>/some_action/

Hope it works.

Body:
The API endpoint is something like that, at django backend
/accounts/id/uuid:pk/some_action/

in the models it is defined as

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

The apiview accepts requests and pk which is uuid as pk.

@api_view(['PUT'])
def some_action(request, pk):

when i'm making a request with uuid it is giving me following error

Not Found: /accounts/user/{id}/some-action/
[12/Feb/2022 18:41:28] "PUT /accounts/id/%7Bid%7D/some-action/ HTTP/1.1" 404 4930

in Postman i configure the url like this /accounts/id/{id}/some-action/

So what might be the problem in passing the uuid ?


问:
How to set the color of unsafe area in a NavigationView
I want the color above the titlebar of NavigationView to remain the same, even when I scroll the list. I've tried using UINavigationBar to set it, but it doesn't work in unsafe area, and tt still turns gray when sliding down.

import SwiftUI

struct ContentView: View {
    init(){
        UINavigationBar.appearance().backgroundColor = UIColor.blue // it doesn't works in unsafe area
    }

    var body: some View {
        TabView {
            NavigationView{
                List{
                    ForEach((1...10).reversed(), id: \.self) {
                        Text("list \($0)")
                    }
                }.toolbar(content: {
                    ToolbarItem(placement: .principal, content: {
                        Text("Title Bar")
                            .bold()
                            .frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .center)
                            .background(Color.red) // it doesn't works
                    })})
                    .navigationBarTitleDisplayMode(.inline)
            }.tabItem {
                Image(systemName: "person")
                Text("tag1")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

```

the preview

答:
I refer to this link https://stackoverflow.com/a/62125578/6845277 to solve this problem.

It feels quite troublesome. I don't know a simple solution yet

import SwiftUI

struct ContentView: View {

    var body: some View {
        TabView {
            NavigationView{
                List{
                    ForEach((1...10).reversed(), id: \.self) {
                        Text("list \($0)")
                    }
                }.toolbar(content: {
                    ToolbarItem(placement: .principal, content: {
                        Text("Title Bar")
                    })})
                    .navigationBarColor(backgroundColor: .blue, titleColor: .white)

                    .navigationBarTitleDisplayMode(.inline)
            }.tabItem {
                Image(systemName: "person")
                Text("tag1")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct NavigationBarModifier: ViewModifier {
    var backgroundColor: UIColor?
    var titleColor: UIColor?

    init(backgroundColor: UIColor?, titleColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = backgroundColor
        coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]

        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    }

    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}
extension View{
    func navigationBarColor(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
    }
}

```

preview

Body:
I want the color above the titlebar of NavigationView to remain the same, even when I scroll the list. I've tried using UINavigationBar to set it, but it doesn't work in unsafe area, and tt still turns gray when sliding down.

import SwiftUI

struct ContentView: View {
    init(){
        UINavigationBar.appearance().backgroundColor = UIColor.blue // it doesn't works in unsafe area
    }

    var body: some View {
        TabView {
            NavigationView{
                List{
                    ForEach((1...10).reversed(), id: \.self) {
                        Text("list \($0)")
                    }
                }.toolbar(content: {
                    ToolbarItem(placement: .principal, content: {
                        Text("Title Bar")
                            .bold()
                            .frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .center)
                            .background(Color.red) // it doesn't works
                    })})
                    .navigationBarTitleDisplayMode(.inline)
            }.tabItem {
                Image(systemName: "person")
                Text("tag1")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

the preview

Body:
I refer to this link https://stackoverflow.com/a/62125578/6845277 to solve this problem.

It feels quite troublesome. I don't know a simple solution yet

import SwiftUI

struct ContentView: View {

    var body: some View {
        TabView {
            NavigationView{
                List{
                    ForEach((1...10).reversed(), id: \.self) {
                        Text("list \($0)")
                    }
                }.toolbar(content: {
                    ToolbarItem(placement: .principal, content: {
                        Text("Title Bar")
                    })})
                    .navigationBarColor(backgroundColor: .blue, titleColor: .white)

                    .navigationBarTitleDisplayMode(.inline)
            }.tabItem {
                Image(systemName: "person")
                Text("tag1")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct NavigationBarModifier: ViewModifier {
    var backgroundColor: UIColor?
    var titleColor: UIColor?

    init(backgroundColor: UIColor?, titleColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = backgroundColor
        coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]

        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    }

    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}
extension View{
    func navigationBarColor(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: backgroundColor, titleColor: titleColor))
    }
}

preview


问:
Animation only works when moving the mouse
I am using Pygame and I have to adapt the following code thus the animation is also showing when the mouse is not moved (so there is no event). Can someone maybe help me please?

The "DDR.png" is attached below. I tried out several things, also by including the updates in the for loop of the main while-running-loop, but it didn't work yet. (You can also in-/decrease the velocity of the robot by pressing t or g).

```<code>import pygame
import math

class Envir:
    def __init__(self,dimentions):
        # colors
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)
        self.green = (0, 255, 0)
        self.blue = (0, 0, 255)
        self.red = (255, 0, 0)
        self.yel = (255, 255, 0)
        # map dims
        self.height=dimentions[0]
        self.width=dimentions[1]
        # window settings
        pygame.display.set_caption("Differential drive robot")
        self.map=pygame.display.set_mode((self.width,self.height))
        # text variables
        self.font=pygame.font.Font('freesansbold.ttf',50)
        self.text=self.font.render('default',True,self.white,self.black)
        self.textRect=self.text.get_rect()
        self.textRect.center=(dimentions[1]-600,dimentions[0]-100)
        # trail
        self.trail_set=[]

    def write_info(self,Vl,Vr,theta):
        txt=f"Vl = {Vl} Vr = {Vr} theta = {int(math.degrees(theta))}"
        self.text=self.font.render(txt,True,self.white,self.black)
        self.map.blit(self.text,self.textRect)

    def trail(self,pos):
        for i in range(0,len(self.trail_set)-1):
            pygame.draw.line(self.map,self.yel,(self.trail_set[i][0],self.trail_set[i][1]),(self.trail_set[i+1][0],self.trail_set[i+1][1]))
        if self.trail_set.__sizeof__()>30000:
            self.trail_set.pop(0)
        self.trail_set.append(pos)

    def robot_frame(self,pos,rotation):
        n=30

        centerx,centery=pos
        x_axis=(centerx + n*math.cos(-rotation),centery + n*math.sin(-rotation))
        y_axis=(centerx + n*math.cos(-rotation+math.pi/2),centery + n*math.sin(-rotation+math.pi/2))
        pygame.draw.line(self.map,self.red,(centerx,centery),x_axis,3)
        pygame.draw.line(self.map,self.green,(centerx,centery),y_axis, 3)

class Robot:
    def __init__(self,startpos,robotImg,width):
        self.m2p=3779.52 # meters 2 pixels
        #robot dims
        self.w=width
        self.x=startpos[0]
        self.y=startpos[1]
        self.theta=0
        self.vl=0.05*self.m2p # meters/2
        self.vr=0.05*self.m2p
        self.maxspeed=0.02*self.m2p
        self.minspeed=0.02*self.m2p
        # graphics
        self.img=pygame.image.load(robotImg)
        self.rotated=self.img
        self.rect=self.rotated.get_rect(center=(self.x,self.y))
    def draw(self,map):
        map.blit(self.rotated,self.rect)

    def move(self,event=None):

        if event is not None:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_s:
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_o:
                    self.vr += 0.001 * self.m2p
                elif event.key == pygame.K_l:
                    self.vr -= 0.001 * self.m2p
                elif event.key == pygame.K_t:
                    self.vr += 0.001 * self.m2p
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_g:
                    self.vr -= 0.001 * self.m2p
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_x:
                    self.vr = 0
                    self.vl = 0

            self.x+=((self.vl+self.vr)/2)*math.cos(self.theta)*dt
            self.y-=((self.vl+self.vr)/2)*math.sin(self.theta)*dt
            self.theta+=(self.vr-self.vl)/self.w*dt

            self.rotated=pygame.transform.rotozoom(self.img,math.degrees(self.theta),1)
            self.rect=self.rotated.get_rect(center=(self.x,self.y))

# initialisation
pygame.init()

# start position
start=(200,200)

#dimentions
dims=(600,1200)

#running or not
running=True

# the envir
environment=Envir(dims)

# the robot
robot=Robot(start,"DDR.png",80)#0.01*3779.52
# dt
dt=0
lasttime=pygame.time.get_ticks()
# simulation loop
while running:
    # activate the quit button
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        robot.move(event)
    dt = (pygame.time.get_ticks() - lasttime) / 1000
    lasttime=pygame.time.get_ticks()
    pygame.display.update()
    environment.map.fill(environment.black)
    robot.move()
    environment.write_info(int(robot.vl), int(robot.vr), robot.theta)
    robot.draw(environment.map)
    environment.robot_frame((robot.x,robot.y),robot.theta)
    environment.trail((robot.x,robot.y))
</code>```

The image "DDR.png":

答:
You have to split the move method. You need one method that handles the events and changes the motion vector and another method that moves the robot:

class Robot:
    # [...]

    def update(self,event=None):

        if event is not None:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_s:
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_o:
                    self.vr += 0.001 * self.m2p
                elif event.key == pygame.K_l:
                    self.vr -= 0.001 * self.m2p
                elif event.key == pygame.K_t:
                    self.vr += 0.001 * self.m2p
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_g:
                    self.vr -= 0.001 * self.m2p
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_x:
                    self.vr = 0
                    self.vl = 0

    def move(self, dt):

        self.x+=((self.vl+self.vr)/2)*math.cos(self.theta)*dt
        self.y-=((self.vl+self.vr)/2)*math.sin(self.theta)*dt
        self.theta+=(self.vr-self.vl)/self.w*dt

        self.rotated=pygame.transform.rotozoom(self.img,math.degrees(self.theta),1)
        self.rect=self.rotated.get_rect(center=(self.x,self.y))
```
<p>Call <code>update</code> in the event loop and <code>move</code> in the application loop:</p>
<pre class="lang-py prettyprint-override"><code>while running:
    # activate the quit button
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        robot.update(event)

    dt = (pygame.time.get_ticks() - lasttime) / 1000
    robot.move(dt)

    # [...]
</code>```

I recommend reading How can I make a sprite move when key is held down.

Body:
I am using Pygame and I have to adapt the following code thus the animation is also showing when the mouse is not moved (so there is no event). Can someone maybe help me please?

The "DDR.png" is attached below. I tried out several things, also by including the updates in the for loop of the main while-running-loop, but it didn't work yet. (You can also in-/decrease the velocity of the robot by pressing t or g).

import pygame
import math

class Envir:
    def __init__(self,dimentions):
        # colors
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)
        self.green = (0, 255, 0)
        self.blue = (0, 0, 255)
        self.red = (255, 0, 0)
        self.yel = (255, 255, 0)
        # map dims
        self.height=dimentions[0]
        self.width=dimentions[1]
        # window settings
        pygame.display.set_caption("Differential drive robot")
        self.map=pygame.display.set_mode((self.width,self.height))
        # text variables
        self.font=pygame.font.Font('freesansbold.ttf',50)
        self.text=self.font.render('default',True,self.white,self.black)
        self.textRect=self.text.get_rect()
        self.textRect.center=(dimentions[1]-600,dimentions[0]-100)
        # trail
        self.trail_set=[]

    def write_info(self,Vl,Vr,theta):
        txt=f"Vl = {Vl} Vr = {Vr} theta = {int(math.degrees(theta))}"
        self.text=self.font.render(txt,True,self.white,self.black)
        self.map.blit(self.text,self.textRect)

    def trail(self,pos):
        for i in range(0,len(self.trail_set)-1):
            pygame.draw.line(self.map,self.yel,(self.trail_set[i][0],self.trail_set[i][1]),(self.trail_set[i+1][0],self.trail_set[i+1][1]))
        if self.trail_set.__sizeof__()>30000:
            self.trail_set.pop(0)
        self.trail_set.append(pos)

    def robot_frame(self,pos,rotation):
        n=30

        centerx,centery=pos
        x_axis=(centerx + n*math.cos(-rotation),centery + n*math.sin(-rotation))
        y_axis=(centerx + n*math.cos(-rotation+math.pi/2),centery + n*math.sin(-rotation+math.pi/2))
        pygame.draw.line(self.map,self.red,(centerx,centery),x_axis,3)
        pygame.draw.line(self.map,self.green,(centerx,centery),y_axis, 3)

class Robot:
    def __init__(self,startpos,robotImg,width):
        self.m2p=3779.52 # meters 2 pixels
        #robot dims
        self.w=width
        self.x=startpos[0]
        self.y=startpos[1]
        self.theta=0
        self.vl=0.05*self.m2p # meters/2
        self.vr=0.05*self.m2p
        self.maxspeed=0.02*self.m2p
        self.minspeed=0.02*self.m2p
        # graphics
        self.img=pygame.image.load(robotImg)
        self.rotated=self.img
        self.rect=self.rotated.get_rect(center=(self.x,self.y))
    def draw(self,map):
        map.blit(self.rotated,self.rect)

    def move(self,event=None):

        if event is not None:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_s:
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_o:
                    self.vr += 0.001 * self.m2p
                elif event.key == pygame.K_l:
                    self.vr -= 0.001 * self.m2p
                elif event.key == pygame.K_t:
                    self.vr += 0.001 * self.m2p
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_g:
                    self.vr -= 0.001 * self.m2p
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_x:
                    self.vr = 0
                    self.vl = 0

            self.x+=((self.vl+self.vr)/2)*math.cos(self.theta)*dt
            self.y-=((self.vl+self.vr)/2)*math.sin(self.theta)*dt
            self.theta+=(self.vr-self.vl)/self.w*dt

            self.rotated=pygame.transform.rotozoom(self.img,math.degrees(self.theta),1)
            self.rect=self.rotated.get_rect(center=(self.x,self.y))

# initialisation
pygame.init()

# start position
start=(200,200)

#dimentions
dims=(600,1200)

#running or not
running=True

# the envir
environment=Envir(dims)

# the robot
robot=Robot(start,"DDR.png",80)#0.01*3779.52
# dt
dt=0
lasttime=pygame.time.get_ticks()
# simulation loop
while running:
    # activate the quit button
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        robot.move(event)
    dt = (pygame.time.get_ticks() - lasttime) / 1000
    lasttime=pygame.time.get_ticks()
    pygame.display.update()
    environment.map.fill(environment.black)
    robot.move()
    environment.write_info(int(robot.vl), int(robot.vr), robot.theta)
    robot.draw(environment.map)
    environment.robot_frame((robot.x,robot.y),robot.theta)
    environment.trail((robot.x,robot.y))

The image "DDR.png":

Body:
You have to split the move method. You need one method that handles the events and changes the motion vector and another method that moves the robot:

class Robot:
    # [...]

    def update(self,event=None):

        if event is not None:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_s:
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_o:
                    self.vr += 0.001 * self.m2p
                elif event.key == pygame.K_l:
                    self.vr -= 0.001 * self.m2p
                elif event.key == pygame.K_t:
                    self.vr += 0.001 * self.m2p
                    self.vl += 0.001 * self.m2p
                elif event.key == pygame.K_g:
                    self.vr -= 0.001 * self.m2p
                    self.vl -= 0.001 * self.m2p
                elif event.key == pygame.K_x:
                    self.vr = 0
                    self.vl = 0

    def move(self, dt):

        self.x+=((self.vl+self.vr)/2)*math.cos(self.theta)*dt
        self.y-=((self.vl+self.vr)/2)*math.sin(self.theta)*dt
        self.theta+=(self.vr-self.vl)/self.w*dt

        self.rotated=pygame.transform.rotozoom(self.img,math.degrees(self.theta),1)
        self.rect=self.rotated.get_rect(center=(self.x,self.y))

Call update in the event loop and move in the application loop:

while running:
    # activate the quit button
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        robot.update(event)

    dt = (pygame.time.get_ticks() - lasttime) / 1000
    robot.move(dt)

    # [...]

I recommend reading How can I make a sprite move when key is held down.


问:
how to change button class when i click on it using Jquery?
so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can't find a way to do it

```<code><html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        $(this).toggleClass("btn btn-success btn btn-info btn btn-primary");
      });
    });
  </script>
  <style>
    #p {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  </style>
  <body>
    <button id="p" class="btn btn-success">Random button</button>
  </body>
</html>
</code>```

答: You could increment a counter each time the button is clicked and add a class based on the count. 0 = green, 1 = red. Toggle is only for switching between two states like a physical toggle would</p>

Body:
so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can't find a way to do it

    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />

    <button id="p" class="btn btn-success">Random button</button>


问:
try catch or async awaiit in useeffect for jest
I am running my first unit tests in JEST. I installed Jest Fetch Mock but I still receive an error, "The promise rejected with reason FetchError".

I did some reading, and I guess that I need to add an async await or a try catch. Can someone help me with this?

This is the fetch I am making in useEffect.

```<code>const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)

    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);
</code>```

答:
This worked better

const fetchList = async () => {

const newList  =  await fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
.then((res) => res.json())
.then((data) => {
setData(data)
setLoading(false)
})
}
fetchList()
}, [500]);

Body:
I am running my first unit tests in JEST. I installed Jest Fetch Mock but I still receive an error, "The promise rejected with reason FetchError".

I did some reading, and I guess that I need to add an async await or a try catch. Can someone help me with this?

This is the fetch I am making in useEffect.

const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)

    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);


问:
Cannot acces rust struct fields
I have a project where I have a struct that looks like this:

```<code>pub struct Msg1Sender {
    c_u: Vec<u8>,
    secret: StaticSecret,
    X_u: PublicKey,
    static_secret: EphemeralSecret,
    static_public: PublicKey,
    APPEUI : Eui64,
    kid: Vec<u8>,
    auth: [u8; 64], //remove
}
</code>```

that is constructeed like this:

```<code>impl PartyU<Msg1Sender> {

    pub fn new(
        c_u: Vec<u8>,
        ecdh_secret: [u8; 32],
        stat_priv: EphemeralSecret,
        stat_pub: PublicKey,
        APPEUI : Eui64,
        kid: Vec<u8>,
    ) -> PartyU<Msg1Sender> {
        // From the secret bytes, create the DH secret
        let secret = StaticSecret::from(ecdh_secret);
        // and from that build the corresponding public key
        let X_u = PublicKey::from(&secret);
        // Combine the authentication key pair for convenience

        let mut auth = [0; 64];   //remove
        PartyU(Msg1Sender {
            c_u,
            secret,
            X_u,
            static_secret:stat_priv,
            static_public:stat_pub,
            APPEUI,
            kid,
            auth //slettes
        })
    }
    ...
</code>```

and then I have the following code in another file:

```<code>let msg1_sender =
    PartyU::new(u_c_u, u_priv, v_static_priv, v_static_pub,APPEUI, u_kid);

println!("{:?}", msg1_sender.APPEUI);
</code>```

Where I am trying to print a field on the struct.
This I can not do. I get the error:

```<code>no field `APPEUI` on type `oscore::edhoc::PartyU<oscore::edhoc::api::Msg1Sender>`

unknown field

help: one of the expressions' fields has a field of the same name: `0.`
</code>```

Adding pub keywords to the fields I am trying to access makes no difference

Which makes no sense to me. the field exists. Why is this happening?

```<code>EDIT
</code>```

I can now understand that the type I am trying to access is of type

```<code>PartyU<oscore::edhoc::api::Msg1Sender>
</code>```

My mistake.
But If I now try to access the msgsender object by writing:

```<code>msg1_sender.0.APPEUI
</code>```

It still fails with:

```<code>field `0` of struct `oscore::edhoc::PartyU` is private
</code>```

Which again is strange to me, since the struct is public:

```<code>pub struct PartyU<S: PartyUState>(S);

// Necessary stuff for session types
pub trait PartyUState {}
impl PartyUState for Msg1Sender {}
impl PartyUState for Msg2Receiver {}
//impl PartyUState for Msg2Verifier {}
//impl PartyUState for Msg3Sender {}

/// Contains the state to build the first message.
pub struct Msg1Sender {
    c_u: Vec<u8>,
    secret: StaticSecret,
    x_u: PublicKey,
    static_secret: EphemeralSecret,
    static_public: PublicKey,
    pub APPEUI : Eui64,
    kid: Vec<u8>,
    auth: [u8; 64], //remove
}
impl PartyU<Msg1Sender> {
</code>```

What part is it that I need to mark as public?

答:
PartyU is a struct tuple, so in order to access the inner struct you have to access with .0.

Then after that, the Error code is clear:

field 0 of struct oscore::edhoc::PartyU is private

unless marked as pub, struct attributes are private and can only be accessed from the structs current module. You have to options to make them publicly available:

pub makes it public for any scope

pub(crate) makes it public for the crate where the struct lives in

pub struct PartyU(pub Msg1Sender);

pub struct Msg1Sender {
    pub c_u: Vec<u8>,
    pub secret: StaticSecret,
    pub X_u: PublicKey,
    pub static_secret: EphemeralSecret,
    pub static_public: PublicKey,
    pub APPEUI : Eui64,
    pub kid: Vec<u8>,
    pub auth: [u8; 64], //remove
}
```

Title: Cannot acces rust struct fields

Body:
I have a project where I have a struct that looks like this:

pub struct Msg1Sender {
    c_u: Vec<u8>,
    secret: StaticSecret,
    X_u: PublicKey,
    static_secret: EphemeralSecret,
    static_public: PublicKey,
    APPEUI : Eui64,
    kid: Vec<u8>,
    auth: [u8; 64], //remove
}

that is constructeed like this:

impl PartyU<Msg1Sender> {

    pub fn new(
        c_u: Vec<u8>,
        ecdh_secret: [u8; 32],
        stat_priv: EphemeralSecret,
        stat_pub: PublicKey,
        APPEUI : Eui64,
        kid: Vec<u8>,
    ) -> PartyU<Msg1Sender> {
        // From the secret bytes, create the DH secret
        let secret = StaticSecret::from(ecdh_secret);
        // and from that build the corresponding public key
        let X_u = PublicKey::from(&secret);
        // Combine the authentication key pair for convenience

        let mut auth = [0; 64];   //remove
        PartyU(Msg1Sender {
            c_u,
            secret,
            X_u,
            static_secret:stat_priv,
            static_public:stat_pub,
            APPEUI,
            kid,
            auth //slettes
        })
    }
    ...

and then I have the following code in another file:

let msg1_sender =
    PartyU::new(u_c_u, u_priv, v_static_priv, v_static_pub,APPEUI, u_kid);

println!("{:?}", msg1_sender.APPEUI);

Where I am trying to print a field on the struct.
This I can not do. I get the error:

no field `APPEUI` on type `oscore::edhoc::PartyU<oscore::edhoc::api::Msg1Sender>`

unknown field

help: one of the expressions' fields has a field of the same name: `0.`

Adding pub keywords to the fields I am trying to access makes no difference

Which makes no sense to me. the field exists. Why is this happening?

EDIT

I can now understand that the type I am trying to access is of type

PartyU<oscore::edhoc::api::Msg1Sender>

My mistake.
But If I now try to access the msgsender object by writing:

msg1_sender.0.APPEUI

It still fails with:

field `0` of struct `oscore::edhoc::PartyU` is private

Which again is strange to me, since the struct is public:

pub struct PartyU<S: PartyUState>(S);

// Necessary stuff for session types
pub trait PartyUState {}
impl PartyUState for Msg1Sender {}
impl PartyUState for Msg2Receiver {}
//impl PartyUState for Msg2Verifier {}
//impl PartyUState for Msg3Sender {}

/// Contains the state to build the first message.
pub struct Msg1Sender {
    c_u: Vec<u8>,
    secret: StaticSecret,
    x_u: PublicKey,
    static_secret: EphemeralSecret,
    static_public: PublicKey,
    pub APPEUI : Eui64,
    kid: Vec<u8>,
    auth: [u8; 64], //remove
}
impl PartyU<Msg1Sender> {

What part is it that I need to mark as public?


问:
Can't convert Message object from RabbitMQ to java class
I created my RabbitListener to get messages from RabbitMQ queue.

My rabbitMQ message:

```<code>Properties
priority:   0
delivery_mode:  2
headers:
__TypeId__: com.kmb.bank.models.Transfer
content_encoding:   UTF-8
content_type:   application/json
Payload
356 bytes
Encoding: string

{"userAccountNumber":"1111444422221111","title":"123","recipientName":"123","recipientAccountNumber":"1234123412341234","amount":123.0,"localDateTime":{"nano":526106200,"year":2018,"monthValue":11,"dayOfMonth":29,"hour":20,"minute":43,"second":0,"month":"NOVEMBER","dayOfWeek":"THURSDAY","dayOfYear":333,"chronology":{"id":"ISO","calendarType":"iso8601"}}}
</code>```

My Listener method:

```<code>@Autowired
private Jackson2JsonMessageConverter jackson2JsonMessageConverter;

@RabbitListener(queues = "kolejka")
public void listen(Message message) {
    try {
        Transfer transfer = (Transfer) jackson2JsonMessageConverter.fromMessage(message);
        log.info(transfer);
    } catch (Exception e) {
        log.debug("Error thrown while listening + " + e.getMessage());
    }

}
</code>```

Bean config:
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

```<code>@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
    return new Jackson2JsonMessageConverter(objectMapper());
}
</code>```

And Transfer class:

```<code>package com.kmb.transactionlogger.models;

@AllArgsConstructor
public class Transfer {
    @Getter @Setter
    private String userAccountNumber;
    @Getter @Setter
    private String title;
    @Getter @Setter
    private String recipientName;
    @Getter @Setter
    private String recipientAccountNumber;
    @Getter @Setter
    private double amount;
    @Getter @Setter
    private LocalDateTime localDateTime;

}
</code>```

Unfortunately the exception is being thrown while converting from Message to Transfer transfer object.

```<code>Caused by: org.springframework.amqp.support.converter.MessageConversionException: failed to resolve class name. Class not found [com.kmb.bank.models.Transfer]
2018-11-29 20:47:01.615  WARN 13688 --- [cTaskExecutor-1] ingErrorHandler$DefaultExceptionStrategy : Fatal message conversion error; message rejected; it will be dropped or routed to a dead letter exchange, if so configured: (Body:'{"userAccountNumber":"1111444422221111","title":"123","recipientName":"123","recipientAccountNumber":"1234123412341234","amount":123.0,"localDateTime":{"nano":599669800,"year":2018,"monthValue":11,"dayOfMonth":29,"hour":20,"minute":47,"second":1,"month":"NOVEMBER","dayOfWeek":"THURSDAY","dayOfYear":333,"chronology":{"id":"ISO","calendarType":"iso8601"}}}' MessageProperties [headers={__TypeId__=com.kmb.bank.models.Transfer}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=bank, receivedRoutingKey=, deliveryTag=2, consumerTag=amq.ctag-sLNqW-_WhDWLWJk6MCQcjg, consumerQueue=kolejka])
</code>```

Whole message log:
https://pastebin.com/raw/47Lq7dYD

答:
I had this issue and when i tried using custom message converters, some would throw errors while trying to resolve to the class specified on the header by the spring producer. I ended up converting the object class to a json string using ObjectMapper class.

One thing i would like to point is that, doing that will send the content to rabbit MQ as a stringified JSON. So you can receive it on the consumer class as a string, map it to another custom class using objectMapper.read(stringType, mappedToClass).

Another advantage i have gotten is that i can directly read it in other consumers written in python or nodejs

In summary
In springboot when sending,

rabbitTemplate.convertAndSend(exchange, key, objectMapper.writeValueAsString()).

In springboot consumer when reading to a custom object that does not have to
match the consumer object.

CustomObj obj = objectMapper.read(incomingString, CustomObj.class).

A point to note is that, make sure to ignoreUnknown fields in the custom object class,

Body:
I created my RabbitListener to get messages from RabbitMQ queue.

My rabbitMQ message:

Properties
priority:   0
delivery_mode:  2
headers:
__TypeId__: com.kmb.bank.models.Transfer
content_encoding:   UTF-8
content_type:   application/json
Payload
356 bytes
Encoding: string

{"userAccountNumber":"1111444422221111","title":"123","recipientName":"123","recipientAccountNumber":"1234123412341234","amount":123.0,"localDateTime":{"nano":526106200,"year":2018,"monthValue":11,"dayOfMonth":29,"hour":20,"minute":43,"second":0,"month":"NOVEMBER","dayOfWeek":"THURSDAY","dayOfYear":333,"chronology":{"id":"ISO","calendarType":"iso8601"}}}

My Listener method:

@Autowired
private Jackson2JsonMessageConverter jackson2JsonMessageConverter;

@RabbitListener(queues = "kolejka")
public void listen(Message message) {
    try {
        Transfer transfer = (Transfer) jackson2JsonMessageConverter.fromMessage(message);
        log.info(transfer);
    } catch (Exception e) {
        log.debug("Error thrown while listening + " + e.getMessage());
    }

}

Bean config:
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
    return new Jackson2JsonMessageConverter(objectMapper());
}

And Transfer class:

package com.kmb.transactionlogger.models;

@AllArgsConstructor
public class Transfer {
    @Getter @Setter
    private String userAccountNumber;
    @Getter @Setter
    private String title;
    @Getter @Setter
    private String recipientName;
    @Getter @Setter
    private String recipientAccountNumber;
    @Getter @Setter
    private double amount;
    @Getter @Setter
    private LocalDateTime localDateTime;

}

Unfortunately the exception is being thrown while converting from Message to Transfer transfer object.

Caused by: org.springframework.amqp.support.converter.MessageConversionException: failed to resolve class name. Class not found [com.kmb.bank.models.Transfer]
2018-11-29 20:47:01.615  WARN 13688 --- [cTaskExecutor-1] ingErrorHandler$DefaultExceptionStrategy : Fatal message conversion error; message rejected; it will be dropped or routed to a dead letter exchange, if so configured: (Body:'{"userAccountNumber":"1111444422221111","title":"123","recipientName":"123","recipientAccountNumber":"1234123412341234","amount":123.0,"localDateTime":{"nano":599669800,"year":2018,"monthValue":11,"dayOfMonth":29,"hour":20,"minute":47,"second":1,"month":"NOVEMBER","dayOfWeek":"THURSDAY","dayOfYear":333,"chronology":{"id":"ISO","calendarType":"iso8601"}}}' MessageProperties [headers={__TypeId__=com.kmb.bank.models.Transfer}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=bank, receivedRoutingKey=, deliveryTag=2, consumerTag=amq.ctag-sLNqW-_WhDWLWJk6MCQcjg, consumerQueue=kolejka])

Whole message log:
https://pastebin.com/raw/47Lq7dYD


问:
Fix: React Native App error: "Task :app:processDebugMainManifest FAILED" with jdk17
I had problems setting up the updated environment for app development with RN.

openjdk version "17.0.1" / node 16+

If you're having the same problem, here's how to solve it:

Error Execution failed for task ':app:processDebugMainManifest'.

答:
Follow this answer i gave a few days ago:
https://stackoverflow.com/a/71007143/15421728

React Native and Gradle Version supported by the latest version of React Native does not support JDK below 11 and above 11.

You need go to Android Studio and download the Temurin/OpenJDK 11 or Azul 11 depending upon your system arch (if you are on the new M1 Mac you will need to download the aarch version).

clean and rebuilding should work after that.


问:
go get specific version
I want to know how go get works, because when im using a libary from github (for example gorilla/mux) the documentation said to install it I should type "go get -u github.com/gorilla/mux", it strange without specific version.!

As far as i know it always use from master branch.
What happen if the owner of the library update the code? Is it gonna be deprecated or something?

Because in my case, im using docker to build the project, every time I build the image, it always do "go get"

Is there any best practice to using go get?

答: You may use go get library@version. For example, go get foo/bar@v1.2.3

Title: go get specific version


问:
App Script - getting the content of a spreedsheet cell and putting it into a text box in a website and clicking the button
I am learning Google App Script and have a question. I am laerning it to do some automation in the future.

Let's assume I have a spreadsheet with cell A1. The content of this cell is "Test"

Let's assume there is a webpage like google. It has a text box and a button(submit button)

I would like to retrieve the content from the cell and put it into the text box. Then I want my script to "click" that button next to it.

Any keyword for me to look for it? Any hint? Am I looking for scrapping or automation? I also would really love to see an example, for example with Google search in order for me to apply it on the actual webpage I am aiming for.

The class name of textbox in Goole Search is class="A8SBwf" and for the button it is class="gNO89b".

Looking forward :))

答:
Here is a quick and dirty example.

In the script editor of your Spreadsheet Code.gs

```<code>function onOpen() {
  var menu = SpreadsheetApp.getUi().createMenu("Test");
  menu.addItem("Dialog","showDialog");
  menu.addToUi();
}

// required if you ever expand on a template
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
};

function showDialog() {
  try {
    var html = HtmlService.createTemplateFromFile('HTML_Demo').evaluate();
    SpreadsheetApp.getUi().showModalDialog(html,"Show Demo");
  }
  catch(err) {
    SpreadsheetApp.getUi().alert(err);
  }
}

function getCellA1() {
  try {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
    return sheet.getRange(1,1).getValue();
  }
  catch(err) {
    return err.message;
  }
}
</code>```

Then in the editor create a new HTML file HTML_Demo;

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <input id="A8SBwf" type="text">
    <input id="gNO89b" type="button" value="Click Me" onclick="buttonOnClick()">
    <script>
      function buttonOnClick() {
        try {
          google.script.run.withSuccessHandler(
            function(response) {
              document.getElementById("A8SBwf").value = response;
            }
          ).getCellA1();
        }
        catch(err) {
          alert(err);
        }
      }
    </script>
  </body>
</html>
</code>```

After that you're on your own.

Body:
Here is a quick and dirty example.

In the script editor of your Spreadsheet Code.gs

function onOpen() {
  var menu = SpreadsheetApp.getUi().createMenu("Test");
  menu.addItem("Dialog","showDialog");
  menu.addToUi();
}

// required if you ever expand on a template
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
};

function showDialog() {
  try {
    var html = HtmlService.createTemplateFromFile('HTML_Demo').evaluate();
    SpreadsheetApp.getUi().showModalDialog(html,"Show Demo");
  }
  catch(err) {
    SpreadsheetApp.getUi().alert(err);
  }
}

function getCellA1() {
  try {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
    return sheet.getRange(1,1).getValue();
  }
  catch(err) {
    return err.message;
  }
}

Then in the editor create a new HTML file HTML_Demo;

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <input id="A8SBwf" type="text">
    <input id="gNO89b" type="button" value="Click Me" onclick="buttonOnClick()">
    <script>
      function buttonOnClick() {
        try {
          google.script.run.withSuccessHandler(
            function(response) {
              document.getElementById("A8SBwf").value = response;
            }
          ).getCellA1();
        }
        catch(err) {
          alert(err);
        }
      }
    </script>
  </body>
</html>

After that you're on your own.


问:
ExtJS: MultiSelect Combo in an EditorGrid
There are some nice ComboBoxes for forms (f.e. the LovCombo or the SuperBoxSelect).

I got a ComboBox working in a Grid. But how do I include a MultiSelect ComboBox in an Editor Grid? What is the best approach? Is there any existing code to get started?

Thanks!

答:
Have you tried using the defined xtypes that the controls provide? If you look at the LovCombo for example, you'll see:

```<code>Ext.reg('lovcombo', Ext.ux.form.LovCombo);
</code>```

Inside of your Grid, for each column, define the editor:

```<code>editor: {
    xtype: 'lovcombo'
    ...
}
</code>```

Body:
Have you tried using the defined xtypes that the controls provide? If you look at the LovCombo for example, you'll see:

Ext.reg('lovcombo', Ext.ux.form.LovCombo);

Inside of your Grid, for each column, define the editor:

editor: {
    xtype: 'lovcombo'
    ...
}


问:
How to add tiles provided by other providers in folium?
Here's My Code:

```<code>import folium as fo
map = fo.Map( [28.908099854138516, 76.59597016811227] , tiles= , zoom_start=11 , )
</code>```

Here, i want to add this tile:
Tile Which I want to add

How can i add this to my Code

答:
To set a custom tile, you need to set the attributes and specify the tile. You will also need an API key, so please register at thunderforest.com to get one.

```<code>import folium

lat, lon = 28.908099854138516, 76.59597016811227
zoom_start = 5

attr = '© <a href="http://www.thunderforest.com/">Thunderforest</a>, © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'

#apikey = open('./thunderforest_api_key.txt').read()
tiles = 'https://tile.thunderforest.com/spinal-map/{z}/{x}/{y}.png?apikey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

m = folium.Map(location=[lat, lon], tiles=tiles, attr=attr, zoom_start=zoom_start)

m
</code>```

Body:
Here's My Code:

import folium as fo
map = fo.Map( [28.908099854138516, 76.59597016811227] , tiles= , zoom_start=11 , )

Here, i want to add this tile:
Tile Which I want to add

How can i add this to my Code

Body:
To set a custom tile, you need to set the attributes and specify the tile. You will also need an API key, so please register at thunderforest.com to get one.

import folium

lat, lon = 28.908099854138516, 76.59597016811227
zoom_start = 5

attr = '&copy; <a href="http://www.thunderforest.com/">Thunderforest</a>, &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'

#apikey = open('./thunderforest_api_key.txt').read()
tiles = 'https://tile.thunderforest.com/spinal-map/{z}/{x}/{y}.png?apikey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

m = folium.Map(location=[lat, lon], tiles=tiles, attr=attr, zoom_start=zoom_start)

m


问:
undefined is appending in top of documnet
Trying to create a page using Javascript. when I try to append HTML into the main div I can see the HTML but I'm seeing undefined in the first line of the document.</p>
```<code>const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' }
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  let html;
  return (html += `<div class={alphabets}>
                      <ul>
                          <li id= ${i.id}>
                              ${i.name} ${i.soundtype}
                          </li>
                      </ul>
                  </div`);
})```

All I'm trying to do is create a list item, I don't have any console logs in the file or browser.

can someone please help to understand why I'm seeing undefined in the top line?

[code snippet](https://stackblitz.com/edit/js-jfz9dk?file=index.js)
</code>```

答:
return value directly HTML at start is undefined like this</p>
```<code>const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' },
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  return (`<div class={alphabets}>
                      <ul>
                          <li id= ${i.id}>
                              ${i.name} ${i.soundtype}
                          </li>
                      </ul>
                  </div`);
});

</code>```

Body:
Trying to create a page using Javascript. when I try to append HTML into the main div I can see the HTML but I'm seeing undefined in the first line of the document.

const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' }
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  let html;
  return (html += `

                              ${i.name} ${i.soundtype}

                  </div`);
})```

All I'm trying to do is create a list item, I don't have any console logs in the file or browser.

can someone please help to understand why I'm seeing undefined in the top line?

[code snippet](https://stackblitz.com/edit/js-jfz9dk?file=index.js)

Body:
return value directly HTML at start is undefined like this

const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' },
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  return (`<div class={alphabets}>
                      <ul>
                          <li id= ${i.id}>
                              ${i.name} ${i.soundtype}
                          </li>
                      </ul>
                  </div`);
});


问:
Replacing strings in vector: Every instance replaced by previous found instance
I'm working with a lot of text files I have loaded into R and I'm trying to replace every instance (or tag) of </SPEAKER> with a certain string found earlier in the text file.

Example:
"<BOB> Lots of text here </SPEAKER> <HARRY> More text here by a different speaker </SPEAKER>"

I'd like to replace every instance of "</SPEAKER>" with the name of, say "<BOB>" and "<HARRY>" based on the NAME that has been found earlier, so I'd get this at the end:

"<BOB> Lots of text here </BOB> <HARRY> More text here by a different speaker </HARRY>"

I was thinking of looping through the vector text but as I only have limited experience with R, I wouldn't know how to tackle this.

If anyone has any suggestions for how to do this, possibly even outside of R using Notepad++ or another text/tag editor, I'd most appreciate any help.

Thanks!

答:
Match

<,

word characters (capturing them in capture group 1),

>,

the shortest string (capturing it in capture group 2) until

</SPEAKER>

and then replace that with the

<,

capture group 1,

>,

capture group 2 and

</ followed by

capture group 1 and

>

This gives

```<code>x <- "<BOB> Lots of text here </SPEAKER> <HARRY> More text here by a different speaker </SPEAKER>"

gsub("<(\\w+)>(.*?)</SPEAKER>", "<\\1>\\2</\\1>", x)
## [1] "<BOB> Lots of text here </BOB> <HARRY> More text here by a different speaker </HARRY>"
</code>```

Body:
Match

<,

word characters (capturing them in capture group 1),

>,

the shortest string (capturing it in capture group 2) until

</SPEAKER>

and then replace that with the

<,

capture group 1,

>,

capture group 2 and

</ followed by

capture group 1 and

>

This gives

x <- "<BOB> Lots of text here </SPEAKER> <HARRY> More text here by a different speaker </SPEAKER>"

gsub("<(\\w+)>(.*?)</SPEAKER>", "<\\1>\\2</\\1>", x)
## [1] "<BOB> Lots of text here </BOB> <HARRY> More text here by a different speaker </HARRY>"