问:
Trouble getting Python Appium-Android test to work (connection error)
I am trying to run a Python Appium test. I have all the correct things installed on my Ubuntu machine (Android Studio, Appium, drivers, etc).

When I run the Python script (after starting Appium), I get this error:

selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: Failed to connect 30 times. Aborting.
Stacktrace:

UnknownError: An unknown server-side error occurred while processing
the command. Original error: Failed to connect 30 times. Aborting.
at getResponseForW3CError (/usr/local/lib/node_modules/appium/node_modules/appium-base-driver/lib/protocol/errors.js:804:9)
at asyncHandler (/usr/local/lib/node_modules/appium/node_modules/appium-base-driver/lib/protocol/protocol.js:380:37)

This is my code:

example.py:

```<code>import os

from appium.webdriver import Remote
from appium_flutter_finder.flutter_finder import FlutterElement, FlutterFinder

# Example

driver = Remote('http://127.0.0.1:4723/wd/hub', dict(
    platformName='android',
    automationName='flutter',
    platformVersion='11',
    deviceName='emulator-5554',
    app='/home/ironmantis7x/AndroidStudioProjects/demoflutter_1/build/app/outputs/flutter-apk/app-debug.apk'
))

finder = FlutterFinder()

text_finder = finder.by_text('You have pushed the button this many times:')
text_element = FlutterElement(driver, text_finder)
print(text_element.text)

key_finder = finder.by_value_key("next_route_key")
goto_next_route_element = FlutterElement(driver, key_finder)
print(goto_next_route_element.text)
goto_next_route_element.click()

back_finder = finder.page_back()
back_element = FlutterElement(driver, back_finder)
back_element.click()

tooltip_finder = finder.by_tooltip("Increment")
driver.execute_script('flutter:waitFor', tooltip_finder, 100)

floating_button_element = FlutterElement(driver, tooltip_finder)
floating_button_element.click()

counter_finder = finder.by_value_key("counter")
counter_element = FlutterElement(driver, counter_finder)
print(counter_element.text)
</code>```

I am not sure why the session is not connecting. I see the app in the emulator open up.

Body:
I am trying to run a Python Appium test. I have all the correct things installed on my Ubuntu machine (Android Studio, Appium, drivers, etc).

When I run the Python script (after starting Appium), I get this error:

selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: Failed to connect 30 times. Aborting.
Stacktrace:

UnknownError: An unknown server-side error occurred while processing
the command. Original error: Failed to connect 30 times. Aborting.
at getResponseForW3CError (/usr/local/lib/node_modules/appium/node_modules/appium-base-driver/lib/protocol/errors.js:804:9)
at asyncHandler (/usr/local/lib/node_modules/appium/node_modules/appium-base-driver/lib/protocol/protocol.js:380:37)

This is my code:

example.py:

import os

from appium.webdriver import Remote
from appium_flutter_finder.flutter_finder import FlutterElement, FlutterFinder

# Example

driver = Remote('http://127.0.0.1:4723/wd/hub', dict(
    platformName='android',
    automationName='flutter',
    platformVersion='11',
    deviceName='emulator-5554',
    app='/home/ironmantis7x/AndroidStudioProjects/demoflutter_1/build/app/outputs/flutter-apk/app-debug.apk'
))

finder = FlutterFinder()

text_finder = finder.by_text('You have pushed the button this many times:')
text_element = FlutterElement(driver, text_finder)
print(text_element.text)

key_finder = finder.by_value_key("next_route_key")
goto_next_route_element = FlutterElement(driver, key_finder)
print(goto_next_route_element.text)
goto_next_route_element.click()

back_finder = finder.page_back()
back_element = FlutterElement(driver, back_finder)
back_element.click()

tooltip_finder = finder.by_tooltip("Increment")
driver.execute_script('flutter:waitFor', tooltip_finder, 100)

floating_button_element = FlutterElement(driver, tooltip_finder)
floating_button_element.click()

counter_finder = finder.by_value_key("counter")
counter_element = FlutterElement(driver, counter_finder)
print(counter_element.text)

I am not sure why the session is not connecting. I see the app in the emulator open up.


来源: stackexchange

问:
Neither BindingResult nor plain target object for bean name
I've been tinkering with Thymeleaf recently a little bit and I'm trying to setup a basic registration form. I have set up my @GetMapping and @Postmapping controller handlers.

Controller:

@GetMapping("/registration")
public String userResponseEntity(Model model) {
    UserModel userModel = new UserModel();
    model.addAttribute("userModel", userModel);
    return "registration";
}

@PostMapping("/registration")
public String userRegistration(@Valid @ModelAttribute("userModel") UserModel user, BindingResult result){
    UserModel userToSubmit = new UserModel();
    userToSubmit.setUsername(user.getUsername());
    userToSubmit.setFirstName(user.getFirstName());
    userToSubmit.setLastName(user.getLastName());

    try {
        User userReturned = userService.saveUser(userToSubmit).orElseThrow(
                () -> new UserException(HttpStatus.BAD_REQUEST, "Unable to register user with given inputs"));
    }catch (UserException e){
        if(result.hasErrors()) {
            logger.error("Could not save the given user to the database");
            return "registration?error=true";
        }
    }
    logger.info(String.format("User: %s has been registered successfully", userToSubmit.getUsername()));
    return "registration?user-created=true";
}
```
<p>The error I have been getting occurs when I click on a button that is not shown in the controller to minimizing purposes, but has the following href from a button located at <code>/login</code></p>
<pre class="lang-html prettyprint-override"><code><p>Not a member? Register</p>
</code>```

After I click on that I am not even redirected to /registration, but instead prompted with the following error:

2022-12-21T19:07:11.241-06:00 ERROR 2109 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring6.processor.SpringInputGeneralFieldTagProcessor' (template: "registration" - line 22, col 94)] with root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userDTO' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153) ~[spring-webmvc-6.0.2.jar:6.0.2]
```
<p><strong>The Thymeleaf template:</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
          crossorigin="anonymous"/>
</head>
    <body>
        <div class="container-fluid text-left">
            <div class="row justify-content-md-center mt-3">
                <div class="col-4">
                    <h3 class="fw-normal mb-3 pb-3 text-center" style="letter-spacing: 1px;">Register Account</h3>
                    <div th:if="${param.error}">//fields has errors
                        <p class="text-danger">[[${session.SPRING_SECURITY_LAST_EXCEPTION.message}]]</p>
                    </div>
                    <form th:action="@{/registration}" method="post" th:object="${userModel}">
                        <div class="form-group">
                            <label for="exampleInputEmail1" class="text-left">Email address</label>
                            <input type="email" class="form-control" id="exampleInputEmail1" th:field="*{username}" aria-describedby="emailHelp" placeholder="Enter email">
                        </div>
                        <div class="form-group">
                            <label for="InputPassword" class="text-left">Password</label>
                            <input type="password" class="form-control" th:field="*{password}" id="InputPassword" placeholder="Password">
                            <label for="ReenterPassword" class="text-left">Re-enter Password</label>
                            <input type="password" class="form-control" th:field="*{password}" id="ReenterPassword" placeholder="Enter password again">
                        </div>
                        <div class="form-group form-check">
                            <input type="checkbox" class="form-check-input" id="exampleCheck1">
                            <label class="form-check-label" for="exampleCheck1">Check me out</label>
                        </div>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been tinkering with Thymeleaf recently a little bit and I'm trying to setup a basic registration form. I have set up my @GetMapping and @Postmapping controller handlers.

Controller:

@GetMapping("/registration")
public String userResponseEntity(Model model) {
    UserModel userModel = new UserModel();
    model.addAttribute("userModel", userModel);
    return "registration";
}

@PostMapping("/registration")
public String userRegistration(@Valid @ModelAttribute("userModel") UserModel user, BindingResult result){
    UserModel userToSubmit = new UserModel();
    userToSubmit.setUsername(user.getUsername());
    userToSubmit.setFirstName(user.getFirstName());
    userToSubmit.setLastName(user.getLastName());

    try {
        User userReturned = userService.saveUser(userToSubmit).orElseThrow(
                () -> new UserException(HttpStatus.BAD_REQUEST, "Unable to register user with given inputs"));
    }catch (UserException e){
        if(result.hasErrors()) {
            logger.error("Could not save the given user to the database");
            return "registration?error=true";
        }
    }
    logger.info(String.format("User: %s has been registered successfully", userToSubmit.getUsername()));
    return "registration?user-created=true";
}

The error I have been getting occurs when I click on a button that is not shown in the controller to minimizing purposes, but has the following href from a button located at /login

Not a member? Register

After I click on that I am not even redirected to /registration, but instead prompted with the following error:

2022-12-21T19:07:11.241-06:00 ERROR 2109 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring6.processor.SpringInputGeneralFieldTagProcessor' (template: "registration" - line 22, col 94)] with root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userDTO' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153) ~[spring-webmvc-6.0.2.jar:6.0.2]

The Thymeleaf template:

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
          crossorigin="anonymous"/>

Register Account

//fields has errors

[[${session.SPRING_SECURITY_LAST_EXCEPTION.message}]]

                    <form th:action="@{/registration}" method="post" th:object="${userModel}">

                            Email address
                            <input type="email" class="form-control" id="exampleInputEmail1" th:field="*{username}" aria-describedby="emailHelp" placeholder="Enter email">

                            Password
                            <input type="password" class="form-control" th:field="*{password}" id="InputPassword" placeholder="Password">
                            Re-enter Password
                            <input type="password" class="form-control" th:field="*{password}" id="ReenterPassword" placeholder="Enter password again">

                            <input type="checkbox" class="form-check-input" id="exampleCheck1">
                            Check me out

                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>


问:
How to improve the success rate of patch download in game development
I am developing a game that uses python as a scripting language and has a module for downloading patches. But the download success rate is only around 95%, I can't have these failures myself, now I want to increase the download success rate further, what scripting language level things can be done (such as parameter Settings, logic tricks), if there is such a todo list.

Common network errors that I collect from users and clients are

time out

No address associated with hostname

Software caused connection abort

I've tried connection pool multiplexing, keep-alive, merging download intervals, increasing repetitions, etc.


问:
Why is Only One Object Appearing in my Database? (Using Spring and MongoDB)
I am working on an ecommerce website using Eclipse, Spring, and MongoDB. Whenever I try creating a new category (URL is http://localhost:8080/admin/categories), the first one appears, but when I try creating a new one, it just replaces my first one. For example, if I create a category called "car", it appears, but then when I create a new one called "bike", the latter takes the place of the former. I of course want category car to be first and category bike to be second. I am assuming it has something to do with the id not saving properly because in my MongoDB collection, the entry shows nothing for _id (normally it does show something for _id).

Here is my code:

```<code>package com.ecommerce.website.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.ecommerce.website.model.Category;
import com.ecommerce.website.service.CategoryService;

@Controller
public class AdminController {

    //Injecting dependency
    @Autowired
    CategoryService categoryService;

    //This method maps for /admin endpoint. It shows the adminHome.html page. The method is @GetMapping because you are getting information
    //@return the adminHome page
    @GetMapping("/admin")
    public String adminHome() {

        //Display html page
        return "adminHome";
    }

    //This method maps for /admin/categories endpoint. It shows the categories.html page. The method is @GetMapping because you are getting information
    //@return the categories page
    @GetMapping("/admin/categories")
    public String getCat(Model model) {

        model.addAttribute("categories", categoryService.getAllCategories());

        //Display html page
        return "categories";
    }

    //This method maps for /admin/categories endpoint. It shows the categoriesAdd.html page, but before that, it creates
    //a model that is sent to the html file via Thymeleaf. The categoriesAdd.html page is a form for adding a category
    //The method is @GetMapping because you are getting information
    //@param model will hold the category object so that the form can add information to it
    //@return the categoriesAdd page
    @GetMapping("/admin/categories/add")
    public String getCatAdd(Model model) {

        //Adding the model name "category", and creating a new Category object and putting it in the model
        model.addAttribute("newCategory", new Category());

        //Display html page
        return "categoriesAdd";
    }

    //This method maps for /admin/categories endpoint. It allows the user to add a category to the list of categories
    //The method is @PostMapping because you are sending information
    //@param category gets its value from the ModelAttribute, which gets its value from the form
    //@return the categories page
    @PostMapping("/admin/categories/add")
    public String postCatAdd(@ModelAttribute("newCategory") Category category) {

        //Calling categoryService to add the category
        categoryService.addCategory(category);

        //Redirecting to page that shows all categories
        return "redirect:/admin/categories";
    }

}
</code>```
```<code>package com.ecommerce.website.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecommerce.website.model.Category;
import com.ecommerce.website.repository.CategoryRepository;

@Service
public class CategoryService {

    //Injecting dependency
    @Autowired
    CategoryRepository categoryRepository;

    //This method calls categoryRepository to add a category to the database
    //@param category is the category that is being added
    public void addCategory(Category category) {

        //Saving the category to the database
        categoryRepository.save(category);
    }

    //This method calls categoryRepository to retrieve a list of categories
    //@return the list of categories
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }
}
</code>```
```<code>package com.ecommerce.website.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.ecommerce.website.model.Category;

public interface CategoryRepository extends MongoRepository<Category, String> {

}
</code>```
```<code>package com.ecommerce.website.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "categories")
public class Category {

    @Id
    private String id;

    private String name;

    public Category() {

    }

    public Category(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code>```

This is the page that is supposed to show all the categories

```<code><!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
          integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
    <title>Document</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light" >
    <div class="container-fluid">
        <a class="navbar-brand" href="#">
            <img th:src="@{/images/logo.png}"  src="../static/images/logo.png" width="auto" height="40" class="d-inline-block align-top" alt=""/>
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto"></ul>
            <ul class="navbar-nav">
                <li class="nav-item active">

                    <!-- This anchor allows the user to go to the admin home page. It maps to the method with
                         /admin endpoint -->
                    <a class="nav-link" th:href="@{/admin}" href="#">admin-home</a>
                </li>
                <li class="nav-item active">

                    <!-- This anchor allows the user to logout. It maps to the method with
                         /logout endpoint -->
                    <a class="nav-link" th:href="@{/logout}" href="#">logout</a>
                </li>

            </ul>

        </div>
    </div>
</nav>
<div class="container">

    <!-- This anchor allows the user to go to the categoriesAdd page. It maps to the method with
         /admin/categories/add endpoint -->
    <a th:href="@{/admin/categories/add}" style="margin: 20px 0" class="btn btn-primary">Add Category</a>
    <table class="table">

        <!-- Creating the table heads -->
        <thead class="thead-light">
        <tr>
            <th scope="col">SN</th>
            <th scope="col">Category Name</th>
            <th scope="col">Delete</th>
            <th scope="col">Update</th>
        </tr>
        </thead>
        <tbody>

        <!-- Looping through each category and displaying its name (iStat is responsible for the serial numbers) -->
        <tr th:each="category, iStat : ${categories}">

            <!-- iStat.index is 0th index, so we add 1 so that the SN's start at 1 -->
            <th scope="row" th:text="${iStat.index + 1}">1</th>
            <td th:text="${category.name}">Larry</td>

            <!-- ????Buttons: first deletes the product; second maps to the /update endpoint, which takes the user to edit.html
                         for whichever product the product.id is for (id is appended to the URL, which is how the /show endpoint
                         is able to access it -->
            <td><a href="" th:href="@{/admin/categories/delete/{id}(id=${category.id})}" class="btn btn-danger">Delete</a></td>
            <td><a href="" th:href="@{/admin/categories/update/{id}(id=${category.id})}" class="btn btn-warning">Update</a></td>

        </tr>
        </tbody>
    </table>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
</code>```

This is the page for adding a new category

```<code><!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
          integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
    <title>Document</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light" >
    <div class="container-fluid">
        <a class="navbar-brand" href="#">
            <img th:src="@{/images/logo.png}"  src="../static/images/logo.png" width="auto" height="40" class="d-inline-block align-top" alt=""/>
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto"></ul>
            <ul class="navbar-nav">
                <li class="nav-item active">
                    <a class="nav-link" th:href="@{/admin}" href="#">admin-home</a>
                </li>
                <li class="nav-item active">
                    <a class="nav-link" th:href="@{/logout}" href="#">logout</a>
                </li>

            </ul>

        </div>
    </div>
</nav>
<div class="container">
    <div class="row">
        <div class="col-sm-4">

            <!-- Mapping to the /admin/categories/add endpoint (@PostMapping one). We are using post method since we are
                 sending info. The category object comes from the getCatAdd() method -->
            <!-- This is the real work: send form data to /admin/categories/add. "category" is the model attribute -->
            <form th:action="@{/admin/categories/add}" method="post" th:object="${newCategory}">

                <!-- Hidden id field to show which category is being added. It will bind to ModelAttribute to tell your app
                     which category is being added. *{category_id} selects category_id property on referenced th:object (category)  -->
                <input type="hidden" name="id" th:field="*{id}">

                <div class="form-group">
                    <label for="name">Name</label>

                    <!-- Input field. *{name} selects name property on referenced th:object (category) -->
                    <input type="text" class="form-control" required th:field="*{name}" name="name" id="name"  placeholder="Enter name">

                </div>

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
</code>```

Body:
I am working on an ecommerce website using Eclipse, Spring, and MongoDB. Whenever I try creating a new category (URL is http://localhost:8080/admin/categories), the first one appears, but when I try creating a new one, it just replaces my first one. For example, if I create a category called "car", it appears, but then when I create a new one called "bike", the latter takes the place of the former. I of course want category car to be first and category bike to be second. I am assuming it has something to do with the id not saving properly because in my MongoDB collection, the entry shows nothing for _id (normally it does show something for _id).

Here is my code:

package com.ecommerce.website.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.ecommerce.website.model.Category;
import com.ecommerce.website.service.CategoryService;

@Controller
public class AdminController {

    //Injecting dependency
    @Autowired
    CategoryService categoryService;

    //This method maps for /admin endpoint. It shows the adminHome.html page. The method is @GetMapping because you are getting information
    //@return the adminHome page
    @GetMapping("/admin")
    public String adminHome() {

        //Display html page
        return "adminHome";
    }

    //This method maps for /admin/categories endpoint. It shows the categories.html page. The method is @GetMapping because you are getting information
    //@return the categories page
    @GetMapping("/admin/categories")
    public String getCat(Model model) {

        model.addAttribute("categories", categoryService.getAllCategories());

        //Display html page
        return "categories";
    }

    //This method maps for /admin/categories endpoint. It shows the categoriesAdd.html page, but before that, it creates
    //a model that is sent to the html file via Thymeleaf. The categoriesAdd.html page is a form for adding a category
    //The method is @GetMapping because you are getting information
    //@param model will hold the category object so that the form can add information to it
    //@return the categoriesAdd page
    @GetMapping("/admin/categories/add")
    public String getCatAdd(Model model) {

        //Adding the model name "category", and creating a new Category object and putting it in the model
        model.addAttribute("newCategory", new Category());

        //Display html page
        return "categoriesAdd";
    }

    //This method maps for /admin/categories endpoint. It allows the user to add a category to the list of categories
    //The method is @PostMapping because you are sending information
    //@param category gets its value from the ModelAttribute, which gets its value from the form
    //@return the categories page
    @PostMapping("/admin/categories/add")
    public String postCatAdd(@ModelAttribute("newCategory") Category category) {

        //Calling categoryService to add the category
        categoryService.addCategory(category);

        //Redirecting to page that shows all categories
        return "redirect:/admin/categories";
    }

}

package com.ecommerce.website.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecommerce.website.model.Category;
import com.ecommerce.website.repository.CategoryRepository;

@Service
public class CategoryService {

    //Injecting dependency
    @Autowired
    CategoryRepository categoryRepository;

    //This method calls categoryRepository to add a category to the database
    //@param category is the category that is being added
    public void addCategory(Category category) {

        //Saving the category to the database
        categoryRepository.save(category);
    }

    //This method calls categoryRepository to retrieve a list of categories
    //@return the list of categories
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }
}

package com.ecommerce.website.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.ecommerce.website.model.Category;

public interface CategoryRepository extends MongoRepository<Category, String> {

}

package com.ecommerce.website.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "categories")
public class Category {

    @Id
    private String id;

    private String name;

    public Category() {

    }

    public Category(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

This is the page that is supposed to show all the categories

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
          integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
    <title>Document</title>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    admin-home

                    logout

    Add Category

            SN
            Category Name
            Delete
            Update

            1
            Larry

            Delete
            Update

This is the page for adding a new category

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
          integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
    <title>Document</title>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    admin-home

                    logout

            <form th:action="@{/admin/categories/add}" method="post" th:object="${newCategory}">

                <input type="hidden" name="id" th:field="*{id}">

                    Name

                    <input type="text" class="form-control" required th:field="*{name}" name="name" id="name"  placeholder="Enter name">

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>


问:
Unable to apply functions to column names in dplyr
I have a dataframe df and I wish to create a new column b that is the smaller value of column a and 10 - a. When there is NA, I wish column b also returnsNA in the corresponding rows. So column b should be c(1, 3, 1, NA). I tried the following code but all rows of b are 1. I wish to find a solution in tidyverse.

```<code>library(tidyverse)
df <- data.frame(a = c(1, 3, 9, NA))
df2 <- df %>% mutate(b = min(a, 10 - a, na.rm = T))
</code>```

I guess the issue arises becuase of applying the min function, which is complicated by the presence of NA. But I cannot figure out how to solve the issue.

Body:
I have a dataframe df and I wish to create a new column b that is the smaller value of column a and 10 - a. When there is NA, I wish column b also returnsNA in the corresponding rows. So column b should be c(1, 3, 1, NA). I tried the following code but all rows of b are 1. I wish to find a solution in tidyverse.

library(tidyverse)
df <- data.frame(a = c(1, 3, 9, NA))
df2 <- df %>% mutate(b = min(a, 10 - a, na.rm = T))

I guess the issue arises becuase of applying the min function, which is complicated by the presence of NA. But I cannot figure out how to solve the issue.


问:
i can't show text on the window using SDL2 TTF library
I make a SDL_ttf test code:

```<code>#include <SDL.h>
#include <stdbool.h>
#include <iostream>
#include "SDLwindow.h"
#include <SDL_ttf.h>
#include "GraphLib.h"
#undef main

using namespace std;

int main() {

    bool running = 1;

    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
    TTF_Init();

    WindowSDL window1;
    TTF_Font* font = TTF_OpenFont("./acme.ttf", 10);
    SDL_Surface* textSurf = TTF_RenderText_Solid(font, "Hola mundo", {255,0,0});
    SDL_Texture* textTexture = SDL_CreateTextureFromSurface(window1.renderer, textSurf);

    SDL_FreeSurface(textSurf);
    SDL_Rect textRect;
    textRect.x = 10;
    textRect.y = 10;
    textRect.w = 400;
    textRect.h = 100;
    //TTF_CloseFont(font);

    window1.CreateWindow("Pix", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 600, SDL_WINDOW_BORDERLESS);
    window1.CreateRenderer(window1.window, -1, 0);

    window1.ChangeBackgroundColor(0xe0e0e0);

    drawLine(window1, 3, 3, 40, 50, 0x0aaf88, 0);
    drawLine(window1, 40, 50, 80, 3, 0x0aaf88, 0);
    drawLine(window1, 80, 3, 3, 3, 0x0aaf88, 0);

    SDL_RenderCopy(window1.renderer, textTexture, NULL, &textRect);
    SDL_RenderPresent(window1.renderer);

    while (running) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = 0;
            }
        }

    }

    window1.Shutdown();
    TTF_Quit();

    return 0;
}
</code>```

...and... boom it doesn't appear, heres my screen:

I tried to change the order of certain lines like TTF_Init(); and so on, the results were the same, it does not appear on the screen

Body:
I make a SDL_ttf test code:

#include <SDL.h>
#include <stdbool.h>
#include <iostream>
#include "SDLwindow.h"
#include <SDL_ttf.h>
#include "GraphLib.h"
#undef main

using namespace std;

int main() {

    bool running = 1;

    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
    TTF_Init();

    WindowSDL window1;
    TTF_Font* font = TTF_OpenFont("./acme.ttf", 10);
    SDL_Surface* textSurf = TTF_RenderText_Solid(font, "Hola mundo", {255,0,0});
    SDL_Texture* textTexture = SDL_CreateTextureFromSurface(window1.renderer, textSurf);

    SDL_FreeSurface(textSurf);
    SDL_Rect textRect;
    textRect.x = 10;
    textRect.y = 10;
    textRect.w = 400;
    textRect.h = 100;
    //TTF_CloseFont(font);

    window1.CreateWindow("Pix", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 600, SDL_WINDOW_BORDERLESS);
    window1.CreateRenderer(window1.window, -1, 0);

    window1.ChangeBackgroundColor(0xe0e0e0);

    drawLine(window1, 3, 3, 40, 50, 0x0aaf88, 0);
    drawLine(window1, 40, 50, 80, 3, 0x0aaf88, 0);
    drawLine(window1, 80, 3, 3, 3, 0x0aaf88, 0);

    SDL_RenderCopy(window1.renderer, textTexture, NULL, &textRect);
    SDL_RenderPresent(window1.renderer);

    while (running) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = 0;
            }
        }

    }

    window1.Shutdown();
    TTF_Quit();

    return 0;
}

...and... boom it doesn't appear, heres my screen:

I tried to change the order of certain lines like TTF_Init(); and so on, the results were the same, it does not appear on the screen


问:
Why is this path update in DFS correct?
I don’t understand why the paths printed here would be correct.

How does the path parameter not permanently get changed after child nodes are added to the path here?

For example, say I have a graph like
1 with child nodes 2 3, where 2 has child nodes 4 5.

The path upon hitting node 4 will be [1,2,4]. But, from the attached code, why isn’t the path variable still [1,2,4] before entering node 5? There’s nowhere in this code that involves a popping of nodes upon exiting. I just don’t see how the code here makes it such the path is [1,2,5]. Does the answer involve recursive stack frames?

Title: Why is this path update in DFS correct?


问:
Django - How to store existing Data in Variable from Database and Update it with another variable
I am facing an issue but could not get the findings to solve it. I want to update a record into database using a form and want to keep the existing data into a variable and update it using form and keep the updated data into another variable.

i made a solution using session but want another way to solve it.

```<code>def client_edit(request, client_id):
 client = Client.objects.get(id=client_id)
 previous_client_name = client
 if request.method == 'POST':
    form = AddClientForm(request.POST, instance=client)
    if form.is_valid():
        client2 = form.save(commit=False)
        client2.save()

        context = {
            'user': request.user,
            'client': client2,
            'previous_client':previous_client_name,
        }
        return render(request, 'did_app/client_edit.html', context=context)
    else:
        return render(request, 'did_app/client_edit.html', {'form': form})
 else:
    return render(request, 'did_app/client_edit.html', {'client': client})
</code>```

I tried this way but both client and previous_client return the same data.

Body:
I am facing an issue but could not get the findings to solve it. I want to update a record into database using a form and want to keep the existing data into a variable and update it using form and keep the updated data into another variable.

i made a solution using session but want another way to solve it.

def client_edit(request, client_id):
 client = Client.objects.get(id=client_id)
 previous_client_name = client
 if request.method == 'POST':
    form = AddClientForm(request.POST, instance=client)
    if form.is_valid():
        client2 = form.save(commit=False)
        client2.save()

        context = {
            'user': request.user,
            'client': client2,
            'previous_client':previous_client_name,
        }
        return render(request, 'did_app/client_edit.html', context=context)
    else:
        return render(request, 'did_app/client_edit.html', {'form': form})
 else:
    return render(request, 'did_app/client_edit.html', {'client': client})

I tried this way but both client and previous_client return the same data.


问:
How to prevent AWS Glue crawler creating duplicate schema on my table
I have a workflow that creates incremental parquet files daily as events get generated in our system.

Every time it runs it adds a new parquet file in an s3 partition for the day like so

```<code>S3
|->date=1
| |-> XXX.parquet // {name: "alice", app_info.tag_1: "foo", app_info.tag_2: "bar"}
|
|->date=2
  |-> YYY.parquet // {name: "alice", app_info.tag_3: "baz", app_info.tag_2: "bar", app_info.tag_1: "bar"}
</code>```

The problem is my Glue Table schema looks like this after the first run on day 1

```<code>[
  {
    "Name": "name",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_1",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_2",
    "Type": "string"
  },
]
</code>```

which is correct, but after the second run, it gets a completely random amount of fields from day 2 added into the schema like so:

```<code>[
  {
    "Name": "name",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_1",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_2",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_1", // this is from the event from day 2. This is also a
    "Type": "string"          // duplicate from existing schema
  },
  {
    "Name": "app_info.tag_3", // this is from the event from day 2
    "Type": "string"
  },
]
</code>```

The schema field app_info.tag_1 is added to my table again, even though it's already there. Is this the expected behaviour? If so is there documentation for it? Also how do I remove such duplicate?

The schema for app_info.tag is very dynamic so it can be anything and I would like for Glue to add any new fields to the schema without duplicating existing fields, as Athena would complain about duplicate columns then.

I have selected the option to create a single schema for each s3 path, as well as recrawl all, and Update the table definition in the data catalog

TIA

Body:
I have a workflow that creates incremental parquet files daily as events get generated in our system.

Every time it runs it adds a new parquet file in an s3 partition for the day like so

S3
|->date=1
| |-> XXX.parquet // {name: "alice", app_info.tag_1: "foo", app_info.tag_2: "bar"}
|
|->date=2
  |-> YYY.parquet // {name: "alice", app_info.tag_3: "baz", app_info.tag_2: "bar", app_info.tag_1: "bar"}

The problem is my Glue Table schema looks like this after the first run on day 1

[
  {
    "Name": "name",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_1",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_2",
    "Type": "string"
  },
]

which is correct, but after the second run, it gets a completely random amount of fields from day 2 added into the schema like so:

[
  {
    "Name": "name",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_1",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_2",
    "Type": "string"
  },
  {
    "Name": "app_info.tag_1", // this is from the event from day 2. This is also a
    "Type": "string"          // duplicate from existing schema
  },
  {
    "Name": "app_info.tag_3", // this is from the event from day 2
    "Type": "string"
  },
]

The schema field app_info.tag_1 is added to my table again, even though it's already there. Is this the expected behaviour? If so is there documentation for it? Also how do I remove such duplicate?

The schema for app_info.tag is very dynamic so it can be anything and I would like for Glue to add any new fields to the schema without duplicating existing fields, as Athena would complain about duplicate columns then.

I have selected the option to create a single schema for each s3 path, as well as recrawl all, and Update the table definition in the data catalog

TIA


问:
vscode extension limit quickpick to only show N items for shorter height
I am writing a vscode extension to search/grep content of the current document, but the quickpick by default shows 20 items that blocks the view of the content being searched. Is there a way to limit the quick pick to fewer items?

extension link here

thanks


问:
Exception is thrown but try-catch doesn't catch it?
I'm calling a method to get and parse a JSON from a URL. The code structure is as follows:

internal static void CheckIfSettingsExists()
{
    settingsContainer.Values["ApplicationXCurrentVersion"] = Controller.GetCurrentVersionAsync();
}
```
<p>and the <code>GetCurrentVersionAsync()</code> function:</p>
<pre class="lang-cs prettyprint-override"><code>internal static async Task<string> GetCurrentVersionAsync()
{
    string temp = null;

    using HttpClient client = new HttpClient();

    try
    {
        temp = await client.GetStringAsync("https://someurl.cloud.io/api/v4/VersionCheck");
    }
    catch (Exception e)
    {
        App.log.Error("Error fetching version check json from API. Exception raised was: " + e.ToString());
        return temp;
    }
    App.log.Info("Successfully got return for VersionCheck");

    if (temp == null)
    {
        return temp;
    }

    dynamic JsonObj = JsonConvert.DeserializeObject<dynamic>(temp);

    return JsonObj["LatestVersion"].ToString();
}
</code>```

When I was trying to debug what's happening, I saw that after program runs the line temp = await client.GetStringAsync("https://someurl.cloud.io/api/v4/VersionCheck"); instead of executing the catch block, System.ArgumentException: 'The parameter is incorrect.' is thrown at the line that is calling the GetCurrentVersionAsync() (line 3 in the CheckIfSettingsExists()). I don't understand why this is thrown as even if there was an issue with GetStringAsync() function, I already have it in try block. Can someone shine  a light for me why this is happening?

Body:
I'm calling a method to get and parse a JSON from a URL. The code structure is as follows:

internal static void CheckIfSettingsExists()
{
    settingsContainer.Values["ApplicationXCurrentVersion"] = Controller.GetCurrentVersionAsync();
}

and the GetCurrentVersionAsync() function:

internal static async Task<string> GetCurrentVersionAsync()
{
    string temp = null;

    using HttpClient client = new HttpClient();

    try
    {
        temp = await client.GetStringAsync("https://someurl.cloud.io/api/v4/VersionCheck");
    }
    catch (Exception e)
    {
        App.log.Error("Error fetching version check json from API. Exception raised was: " + e.ToString());
        return temp;
    }
    App.log.Info("Successfully got return for VersionCheck");

    if (temp == null)
    {
        return temp;
    }

    dynamic JsonObj = JsonConvert.DeserializeObject<dynamic>(temp);

    return JsonObj["LatestVersion"].ToString();
}

When I was trying to debug what's happening, I saw that after program runs the line temp = await client.GetStringAsync("https://someurl.cloud.io/api/v4/VersionCheck"); instead of executing the catch block, System.ArgumentException: 'The parameter is incorrect.' is thrown at the line that is calling the GetCurrentVersionAsync() (line 3 in the CheckIfSettingsExists()). I don't understand why this is thrown as even if there was an issue with GetStringAsync() function, I already have it in try block. Can someone shine  a light for me why this is happening?


问:
How can I detect if in Android , soft-keyboard's delete has been long pressed when a particular TextInputLauout field is in focus
I have many custom TextInputLayout with custom TextInputEditText views in the XML.
For some TextInputFields I need to give the below feature:

When the field is in focus

Soft keyboard should launch

When the user presses the delete button for long approx (2 secs)

It should clear the content in TextInputEditText

I tried --> Implementing onKeyPreIme(int keyCode, KeyEvent event) in Fragment


问:
How to generalise the parameters with typescript
Here is my code :

```<code>const search:Object<T> = (value:Object<T>) => {
    return value.name;
}

const v1 = {name:'name1', age:12}
const v2 = {name:'name2', city:'chennai'}
const v3 = {name:'name3', village:'Madukarai'}

const getSearch1 = search<Object>(v1);
const getSearch2 = search<Object>(v2);
const getSearch3 = search<Object>(v3);
</code>```

Typescript play ground

I would like to understand my search function to accept the object or array ( at present object ) to consider it's param as a type. how to do it?

I am getting an error as :

```<code>Type 'Object' is not generic.(2315)
</code>```

Body:
Here is my code :

const search:Object<T> = (value:Object<T>) => {
    return value.name;
}

const v1 = {name:'name1', age:12}
const v2 = {name:'name2', city:'chennai'}
const v3 = {name:'name3', village:'Madukarai'}

const getSearch1 = search<Object>(v1);
const getSearch2 = search<Object>(v2);
const getSearch3 = search<Object>(v3);

Typescript play ground

I would like to understand my search function to accept the object or array ( at present object ) to consider it's param as a type. how to do it?

I am getting an error as :

Type 'Object' is not generic.(2315)


问:
JavaDoc getDocComment() doesn't work if there is an annotation on the element
I am trying to use the getDocComment method to grab some javadoc from a variable declaration, however when there is an annotation between the comment and element then getDocComment returns null

For example:

```<code>/**
 * A description of varA
 */
private SomeObject varA;
</code>```

Then I get my output correctly as: * `varA` (`SomeObject`) - A description of varA

However, if I have an annotation on the variable it does not get the description (debugger shows null).

```<code>/**
 * A description of varA
 */
@NotNull
private SomeObject varA;
</code>```

Then I get my output incorrectly as: * `varA` (`SomeObject`) -

Just want to add some additional context as to why I suspect it is the annotation that is breaking this. The documentation for getDocComment() is as follows:

```<code>Returns the text of the documentation ("Javadoc") comment of an element.
A documentation comment of an element is a comment that begins with "/**", ends with a separate "*/", and immediately precedes the element, ignoring white space. Therefore, a documentation comment contains at least three "*" characters. The text returned for the documentation comment is a processed form of the comment as it appears in source code. The leading "/**" and trailing "*/" are removed. For lines of the comment starting after the initial "/**", leading white space characters are discarded as are any consecutive "*" characters appearing after the white space or starting the line. The processed lines are then concatenated together (including line terminators) and returned.
</code>```

Is there a way around this or an alternate method I'm not seeing?

Body:
I am trying to use the getDocComment method to grab some javadoc from a variable declaration, however when there is an annotation between the comment and element then getDocComment returns null

For example:

/**
 * A description of varA
 */
private SomeObject varA;

Then I get my output correctly as: * `varA` (`SomeObject`) - A description of varA

However, if I have an annotation on the variable it does not get the description (debugger shows null).

/**
 * A description of varA
 */
@NotNull
private SomeObject varA;

Then I get my output incorrectly as: * `varA` (`SomeObject`) -

Just want to add some additional context as to why I suspect it is the annotation that is breaking this. The documentation for getDocComment() is as follows:

Returns the text of the documentation ("Javadoc") comment of an element.
A documentation comment of an element is a comment that begins with "/**", ends with a separate "*/", and immediately precedes the element, ignoring white space. Therefore, a documentation comment contains at least three "*" characters. The text returned for the documentation comment is a processed form of the comment as it appears in source code. The leading "/**" and trailing "*/" are removed. For lines of the comment starting after the initial "/**", leading white space characters are discarded as are any consecutive "*" characters appearing after the white space or starting the line. The processed lines are then concatenated together (including line terminators) and returned.

Is there a way around this or an alternate method I'm not seeing?


问:
Service Worker generated by workbox-build can't work in Chrome 50
I use workbox-build to build /sw-workbox.js and add it the my page, it works well in new version of Chrome, but I try to test it in old versions of Chrome like Chrome 50, the debugger shows the errror below:

It seems there is some syntax error in the /sw-workbox.js file, so is there any similar case? And how to configure work-build to build a service worker file which can work well in old versions of browser like Chrome 50?


问:
If .NET source is provided as JavaScript function, function body must be a /* ... */ comment
OS : Windows10 64bit,
vue : 3.x,
nodejs : 14.16.0 32bit,
electron : 13.0.0

Develop with electron-builder in vuejs 3.x.
The command npm run electron:serve works fine, but
When I run npm run electron:build the generated file, I get an error.

<template>

Welcome to Your Vue.js App

    <button @click="testEdge">testEdge</button>

 </template>

 ```
</div>
</div>
</p>
```module.exports = {
pluginOptions: {
    electronBuilder: {
        nodeIntegration: true,
        externals: ['electron-edge-js']
    }
},
```

}

full Source is on github.
https://github.com/xeroyal/edge-test.git

enter image description here

Body:
OS : Windows10 64bit,
vue : 3.x,
nodejs : 14.16.0 32bit,
electron : 13.0.0

Develop with electron-builder in vuejs 3.x.
The command npm run electron:serve works fine, but
When I run npm run electron:build the generated file, I get an error.

<template>

Welcome to Your Vue.js App

    <button @click="testEdge">testEdge</button>

 </template>

module.exports = {
pluginOptions: {
    electronBuilder: {
        nodeIntegration: true,
        externals: ['electron-edge-js']
    }
},

}

full Source is on github.
https://github.com/xeroyal/edge-test.git

enter image description here


问:
Why that property don't apply on the QMenu widget?
I try to make that GUI, but when I try to apply "styleSheet" property it's not working. The code it's working well, I can load that UI in python, but when I try the style of menuFile don't seems to be applied.

There is my code from .ui file:

```<code><widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1280</width>
     <height>21</height>
    </rect>
   </property>
   <property name="autoFillBackground">
    <bool>false</bool>
   </property>
   <property name="styleSheet">
    <string notr="true">QMenuBar{color:white;}</string>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="styleSheet">
     <string notr = "true">
     QMenu {background-color:black;}
     QMenu:hover { background-color: red; }
      </string>
    </property>
    <property name="title">
     <string>File</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuEdit">
    <property name = "styleSheet">
    <string notr="true"></string>
    </property>
    <property name="title">
     <string>Edit</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuHelp">
    <property name="title">
     <string>Help</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuWindow">
    <property name="title">
     <string>Window</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuLayout">
    <property name="title">
     <string>Layout</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuPresentation">
    <property name="title">
     <string>Presentation</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuRender">
    <property name="title">
     <string>Render</string>
    </property>
   </widget>
</code>```

Body:
I try to make that GUI, but when I try to apply "styleSheet" property it's not working. The code it's working well, I can load that UI in python, but when I try the style of menuFile don't seems to be applied.

There is my code from .ui file:

<widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1280</width>
     <height>21</height>
    </rect>
   </property>
   <property name="autoFillBackground">
    <bool>false</bool>
   </property>
   <property name="styleSheet">
    <string notr="true">QMenuBar{color:white;}</string>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="styleSheet">
     <string notr = "true">
     QMenu {background-color:black;}
     QMenu:hover { background-color: red; }
      </string>
    </property>
    <property name="title">
     <string>File</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuEdit">
    <property name = "styleSheet">
    <string notr="true"></string>
    </property>
    <property name="title">
     <string>Edit</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuHelp">
    <property name="title">
     <string>Help</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuWindow">
    <property name="title">
     <string>Window</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuLayout">
    <property name="title">
     <string>Layout</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuPresentation">
    <property name="title">
     <string>Presentation</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuRender">
    <property name="title">
     <string>Render</string>
    </property>
   </widget>


问:
Static Configuration In Apache Spark
Im learning Spark, when reading about:
"Static Configuration", an explained has been followed: "Using when Properties related to the application, not the deployment".
A huge misunderstanding in here is: So what is the different when related to the application and the deployment!
Thanks for your help!

Misunderstanding about the Spark Properties when related to the application and the deployment!

Title: Static Configuration In Apache Spark


问:
Script to move files to desktop folder
I have been working on a small script to help with the setting up of users' workstations and have hit a brick wall.

What I am wanting to accomplish is that by selecting a role in the Listbox and clicking on button0 a network directory gets copied to the current user's desktop.

I am sure I am missing something easy and would greatly appreciate any and all help.
yes, I do love my .bat scripts

Please see the below code I have been working on

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

Imports System.Net.Mail
Imports System.Net.Security

Public Class Form1

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' add items to the listbox
    With lbDepartments
        .Items.Add("Bookings")
        .Items.Add("Logistics")
        .Items.Add("Materials")
        .Items.Add("Programming")
        .Items.Add("Traffic")

    End With
End Sub
Private Sub Button0_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button0.Click
    'Move setup files to desktop
    Dim strDestFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\test\"
    Dim dirinfo As IO.DirectoryInfo
    'Move Bookings files to desktop
    If lbDepartments.SelectedIndex = 0 Then
        Console.WriteLine("The destination folder is " & strDestFolder)
        My.Computer.FileSystem.DirectoryExists(strDestFolder)
        Console.WriteLine("The folder exists!")
    Else
        dirinfo = My.Computer.FileSystem.GetDirectoryInfo(strDestFolder)
        Console.WriteLine("Current file count is " & dirinfo.GetFiles.Count)
        Console.WriteLine("The folder does not exists!")
        Else
        My.Computer.FileSystem.CopyDirectory("c:\temp\tdrive\", strDestFolder, True) Then
            dirinfo = My.Computer.FileSystem.GetDirectoryInfo(strDestFolder)
            Console.WriteLine("File count is now " & dirinfo.GetFiles.Count)
            Console.ReadLine()
        End If
    'If lbDepartments.SelectedIndex = 1 Then
    'End If
    'Copy Logistics files to desktop
    'If lbDepartments.SelectedIndex = 2 Then
    'End If
    'Copy Materials files to desktop
    ' If lbDepartments.SelectedIndex = 3 Then
    'End If
    'Copy Programming files to desktop
    ' If lbDepartments.SelectedIndex = 4 Then
    ' End If
    'Copy Traffic files to desktop
    ' If lbDepartments.SelectedIndex = 5 Then
    'End If

End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ' Change language with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\region.bat")
End Sub

Private Sub Button2_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' change list seperator with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\list_seperator.bat")

End Sub

Private Sub Button3_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' change region with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\region.bat")

End Sub

Private Sub Button4_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' change time and date with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\time_and_date.bat")

End Sub
Private Sub Button5_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' Import Power Plan
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\power_plan.bat")

End Sub
</code>```

End Class

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

Title: Script to move files to desktop folder

Body:
I have been working on a small script to help with the setting up of users' workstations and have hit a brick wall.

What I am wanting to accomplish is that by selecting a role in the Listbox and clicking on button0 a network directory gets copied to the current user's desktop.

I am sure I am missing something easy and would greatly appreciate any and all help.
yes, I do love my .bat scripts

Please see the below code I have been working on

Imports System.Net.Mail
Imports System.Net.Security

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' add items to the listbox
    With lbDepartments
        .Items.Add("Bookings")
        .Items.Add("Logistics")
        .Items.Add("Materials")
        .Items.Add("Programming")
        .Items.Add("Traffic")

    End With
End Sub
Private Sub Button0_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button0.Click
    'Move setup files to desktop
    Dim strDestFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\test\"
    Dim dirinfo As IO.DirectoryInfo
    'Move Bookings files to desktop
    If lbDepartments.SelectedIndex = 0 Then
        Console.WriteLine("The destination folder is " & strDestFolder)
        My.Computer.FileSystem.DirectoryExists(strDestFolder)
        Console.WriteLine("The folder exists!")
    Else
        dirinfo = My.Computer.FileSystem.GetDirectoryInfo(strDestFolder)
        Console.WriteLine("Current file count is " & dirinfo.GetFiles.Count)
        Console.WriteLine("The folder does not exists!")
        Else
        My.Computer.FileSystem.CopyDirectory("c:\temp\tdrive\", strDestFolder, True) Then
            dirinfo = My.Computer.FileSystem.GetDirectoryInfo(strDestFolder)
            Console.WriteLine("File count is now " & dirinfo.GetFiles.Count)
            Console.ReadLine()
        End If
    'If lbDepartments.SelectedIndex = 1 Then
    'End If
    'Copy Logistics files to desktop
    'If lbDepartments.SelectedIndex = 2 Then
    'End If
    'Copy Materials files to desktop
    ' If lbDepartments.SelectedIndex = 3 Then
    'End If
    'Copy Programming files to desktop
    ' If lbDepartments.SelectedIndex = 4 Then
    ' End If
    'Copy Traffic files to desktop
    ' If lbDepartments.SelectedIndex = 5 Then
    'End If

End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ' Change language with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\region.bat")
End Sub

Private Sub Button2_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' change list seperator with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\list_seperator.bat")

End Sub

Private Sub Button3_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' change region with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\region.bat")

End Sub

Private Sub Button4_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' change time and date with batch file
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\time_and_date.bat")

End Sub
Private Sub Button5_click(sender As Object, e As EventArgs) Handles Button3.Click
    ' Import Power Plan
    Shell("O:\Common\COMPUTER_SETUPS\Setup_Scripts\power_plan.bat")

End Sub

End Class


问:
Finding and filtering numbers in arrays and returning only the satisfying conditions
I wish to select the rows that satisfy a few conditions, which may not be done directly through filter command.

I wish to go through each "ID1" using a for loop in 1:max(ID1), then in each loop there could be different numbers of "ID2".

Now given that the conflict type is 12,  like three highlighted 12 in ConflictTypeID, I would like to store the corresponding code of UserTypeA and UserTypeB. If either of UserTypeA and UserTypeB is not 4, then the corresponding User1_id and User2_id should be searched for repetation if any. Given that one of the User1_id or User1_id is being repeated, I should get those two rows in return.

For example the image I have attached, given that ConflictTypeId is 12, I have in UserTypeA and UserTypeB 3 that is is not "4" to be specific. Then,  the corresponding User1_id and User2_id I have 299, which can be repeated in either User1_id and User2_id. Now the end result will then be the ID=762 and 765. All other rows should filter out.

I have tried filtering and for loops, but I am unable to get to required result. Can someone please help me solve this filtering problem.
enter image description here


问:
Angular Virtual Scroll Gets reset upon hitting MinBufferPx
```<code><ng-container *ngIf="infoCardRows?.length > 0">
        <cdk-virtual-scroll-viewport itemSize="44" minBufferPx="132" maxBufferPx="440">
            <ng-container *cdkVirtualFor="let item of infoCardRows;templateCacheSize: 0">
                <info-card-body-row [item]="item" [filter]="filter"></info-card-body-row>
            </ng-container>
        </cdk-virtual-scroll-viewport>
    </ng-container>
</code>```

After certain amount of scrolling, data gets repeated.
While debugging I found out that the, transform: translateY(0px); gets updated and reset simultaneously.

This issue only happens while scrolling slowly. On fast scrolling everything works prefectly. With more and more minBufferPx appearance of this issue can be delayed.

I would like to fix this issue

Body:
<ng-container *ngIf="infoCardRows?.length > 0">
        <cdk-virtual-scroll-viewport itemSize="44" minBufferPx="132" maxBufferPx="440">
            <ng-container *cdkVirtualFor="let item of infoCardRows;templateCacheSize: 0">
                <info-card-body-row [item]="item" [filter]="filter"></info-card-body-row>
            </ng-container>
        </cdk-virtual-scroll-viewport>
    </ng-container>

After certain amount of scrolling, data gets repeated.
While debugging I found out that the, transform: translateY(0px); gets updated and reset simultaneously.

This issue only happens while scrolling slowly. On fast scrolling everything works prefectly. With more and more minBufferPx appearance of this issue can be delayed.

I would like to fix this issue


问:
Facing issue in cypress test while publishing data to rabbit mq
I have a cypress test which has many steps . In the initial steps I publish data to rabbit mq through fetch() method in cypress.intercept. but intermittently publishing fails with "type error : failed to fetch"
I have checked inputs ,url everything is fine. I am suspecting network issue. But this call is to local rmq on Jenkins server . What could be the reason and how to fix it . For now I have put a fix to retry if it fails.

I tried putting catch block and returning resolve promise assuming publish is happening after that network connection error occurred.

I logged url, body ,looks everything fine for me.

Finally  I put a retry in catch block to retry fetch

Code is confidential so can't post it


问:
How batch processing over multiple loops work in Apache Flink?
I wanted to clear my understanding on the following.
Use case

Basically I am running a flink batch job. My requirement is following
I have 10 tables having raw data in postgresql
I want to aggregate that data by creating a tumble window of 10 minutes
I need to store the aggregated data into aggregated postgresql tables

My pseudo code somewhat looks like this

```<code>initialize StreamExecutionEnvironment, StreamTableEnvironment
load all the configs from file
configs.foreach(
load data from table
aggregate
store data
delete temporary views created
)
streamExecutionEnvironment.execute()
</code>```

Everything works fine for now. Still I have gotten one question. I think with this approach all the load functions would be executed simultaneously. So it would put load on flink right as all data is getting loaded simultaneously?? Or my understanding is wrong and the data would get loaded, processed and stored one by one?? please guide

Body:
I wanted to clear my understanding on the following.
Use case

Basically I am running a flink batch job. My requirement is following
I have 10 tables having raw data in postgresql
I want to aggregate that data by creating a tumble window of 10 minutes
I need to store the aggregated data into aggregated postgresql tables

My pseudo code somewhat looks like this

initialize StreamExecutionEnvironment, StreamTableEnvironment
load all the configs from file
configs.foreach(
load data from table
aggregate
store data
delete temporary views created
)
streamExecutionEnvironment.execute()

Everything works fine for now. Still I have gotten one question. I think with this approach all the load functions would be executed simultaneously. So it would put load on flink right as all data is getting loaded simultaneously?? Or my understanding is wrong and the data would get loaded, processed and stored one by one?? please guide


问:
How to fix "cannot toggle freezer: cgroups not configured for container" error
Im getting the below error when I try to stop and rm the running container using podman.

WARN[0000] cannot toggle freezer: cgroups not configured for container WARN[0000] cannot toggle freezer: cgroups not configured for container WARN[0000] lstat : no such file or directory WARN[0000] Failed to remove cgroup (will retry)          error="rmdir /sys/fs/cgroup/systemd/user.slice/user-491465.slice/user@491465.service/user.slice/podman-344715.scope/d8258e0ae3f2a7a7f08abca04446247

I guess due to this some of the running process inside the container is not stopped properly and still available in host process list.

Actually I want to gracefully exit all the process like exiting container like giving 'exit' command when container is attached.

Please let me know how to fix the error or how to gracefully shutdown all the process of running conatainer from host.


问:
How can we use a basic Discrete Wavelet Transform(DWT) in a CNN layer?
How can we use a basic Discrete Wavelet Transform(DWT) in a CNN layer?

If possible can anyone please give a code snippet preferably in python Tensorflow.

I want to use this for a image processing task using deep learning and implement DWT as a filter in CNN network.


问:
Next.js change Image src onClick (TS)
I am trying to create a gallery. Where many images will be created. Though I want my first image to be big[500 x 500 px] and rest of them [80 x 80px].
I want to change the large image src with the clicked imaged src.
I have tried using ref. But its not working.

I am calling an api to get the images.

Currently I am trying with

```<code> const imageRef = React.useRef<HTMLImageElement | null>(null);

 function handleImageClick(e: React.MouseEvent<HTMLImageElement>) {
    console.log(e.target)
    const target = e.target as HTMLImageElement
    imageRef.current!.src = target.src
  }
</code>```

The return statement is

```<code><Image
   ref={imageRef}
   src={imageRef.current?.src || thumbnailImage}
/>
</code>```

From the smaller images list are as

```<code>{images.map((image: string, index: number) => (
    <Image
    onClick={handleImageClick}
    key={index}
    src={image}
/>
))}
</code>```

Title: Next.js change Image src onClick (TS)

Body:
I am trying to create a gallery. Where many images will be created. Though I want my first image to be big[500 x 500 px] and rest of them [80 x 80px].
I want to change the large image src with the clicked imaged src.
I have tried using ref. But its not working.

I am calling an api to get the images.

Currently I am trying with

 const imageRef = React.useRef<HTMLImageElement | null>(null);

 function handleImageClick(e: React.MouseEvent<HTMLImageElement>) {
    console.log(e.target)
    const target = e.target as HTMLImageElement
    imageRef.current!.src = target.src
  }

The return statement is

<Image
   ref={imageRef}
   src={imageRef.current?.src || thumbnailImage}
/>

From the smaller images list are as

{images.map((image: string, index: number) => (
    <Image
    onClick={handleImageClick}
    key={index}
    src={image}
/>
))}


问:
Multiple Websites not working on Nginx Revrese Proxy
One of the website is not accessible via nginx reverse proxy when we have configuration files of two different websites (hosted on two docker containers) palced under /etc/nginx/conf.d. The configuration files are as follows

Website 1: /etc/nginx/conf.d/tr.conf

```<code>server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/tr.crt;
    ssl_certificate_key /etc/nginx/ssl/tr.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5;

    server_name trac.internal.local;
    location /trend {
        proxy_pass http://tr/trend:9090;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect http://tr/trend /;
    }
}
</code>```

Website 2: /etc/nginx/conf.d/pageview.conf

```<code>server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/pageview.crt;
    ssl_certificate_key /etc/nginx/ssl/pageview.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5;

    server_name pageview.internal.local;
    location /pageview {
        proxy_pass http://pageviewfront:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect http://pageviewfront /;
    }
}
</code>```

Body:
One of the website is not accessible via nginx reverse proxy when we have configuration files of two different websites (hosted on two docker containers) palced under /etc/nginx/conf.d. The configuration files are as follows

Website 1: /etc/nginx/conf.d/tr.conf

server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/tr.crt;
    ssl_certificate_key /etc/nginx/ssl/tr.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5;

    server_name trac.internal.local;
    location /trend {
        proxy_pass http://tr/trend:9090;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect http://tr/trend /;
    }
}

Website 2: /etc/nginx/conf.d/pageview.conf

server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/pageview.crt;
    ssl_certificate_key /etc/nginx/ssl/pageview.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5;

    server_name pageview.internal.local;
    location /pageview {
        proxy_pass http://pageviewfront:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect http://pageviewfront /;
    }
}


问:
I want to develop code in vue.Js using vuetify which take input through textfield and display two string values on display after the button click
I am knida new to vue.js please help me to solve problem.

I want to develop code in vue.Js using vuetify which take input through textfield and display two string values on display after the button click.

Here is the code